赞
踩
MySQL作为一个普遍使用的关系型数据库,其性能毋庸置疑,但是当MySQL中的数据太过于庞大时,对查询效率会产生较大的影响,所有我们将过期不常使用的数据迁移到MongoDB中。而MongoDB作为nosql数据库的一种,可以十分方便的存储大规模数据,且它的操作方式和MySQL十分相似,可以说MySQL能够做到的都可以使用MongoDB实现。
1 将MySQL数据提取处理,包括字段名称
2 将提取到的数据转变成json格式
3 存储到MongoDB中
具体如下
1 使用python中的mysql.connector库MySQL数据库:import mysql.connector
,使用pymongo连接mongodb数据库:import pymongo
。
2 从MySQL中读取数据,包括数据的字段名称:
- sql = 'select * from %s where id = %s'%(table_names[1],order_id)
- cursor.execute(sql)
- rows = cursor.fetchall()
- column_names = [d[0] for d in cursor.description]
3 使用继承子dict的类将读取到的数据转换成字典的数组,以便于存入mongodb中
- #定义一个继承自dict的类
- class Row(dict):
- """A dict that allows for object-like property access syntax."""
- def __getattr__(self, name):
- try:
- return self[name]
- except KeyError:
- raise AttributeError(name)
将数据转换成json格式:
- item = [Row(zip(column_names, row)) for row in rows]
- item = item[0]
- if item:
- '''merge_set_by_set是我定义的把多个表相关联的数据表的数据存放到一起组合成一个json的函数'''
- merge_set_by_set(mongo_item, item,table_names[0])
4 将数据存放到mongodb中
- if mongo_items:
- try:
- mongo.order_info1.insert_many(mongo_items)
- print('=success insert into mongodb')
- except:
- print('fail')
至此,就可以完成从MySQL向mongodb迁移数据的脚本了
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。