Python中MySQL数据迁移到MongoDB脚本的方法

yipeiwu_com5年前Python基础

MongoDB简介

MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。

MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。

MongoDB是一个文档数据库,在存储小文件方面存在天然优势。随着业务求的变化,需要将线上MySQL数据库中的行记录,导入到MongoDB中文档记录。

一、场景:线上MySQL数据库某表迁移到MongoDB,字段无变化。

二、Python模块:

使用Python的torndb,pymongo和time模块。

*注释:首先安装setup.py,pip,MySQLdb

执行如下命令即可:

pip install torndb
pip install pymongo

三、脚本内容如下:

[root ~]#cat nmytomongo.py

#!/usr/bin/env python#fielName: mytomongo.py#Author:xkops#coding: utf-8import torndb,pymongo,time# connect to mysql databasemysql = torndb.Connection(host='127.0.0.1', database='database', user='username', password='password')#connect to mongodb and obtain total lines in mysqlmongo = pymongo.MongoClient('mongodb://ip').databasemongo.authenticate('username',password='password')countlines = mysql.query('SELECT max(table_field) FROM table_name')count = countlines[0]['max(table_field)']#count = 300print counti = 0 j = 100start_time = time.time()#select from mysql to insert mongodb by 100 lines.for i in range(0,count,100): #print a,b #print i #print 'SELECT * FROM quiz_submission where quiz_submission_id > %d and quiz_submission_id <= %d' %(i,j) submission = mysql.query('SELECT * FROM table_name where table_field > %d and table_field <= %d' %(i,j)) #print submission if submission: #collection_name like mysql table_name mongo.collection_name.insert_many(submission) else: i +=100 j +=100 continue i +=100 j +=100end_time = time.time()deltatime = end_time - start_timetotalhour = int(deltatime / 3600)totalminute = int((deltatime - totalhour * 3600) / 60)totalsecond = int(deltatime - totalhour * 3600 - totalminute * 60)#print migrate data total time consuming.print "Data Migrate Finished,Total Time Consuming: %d Hour %d Minute %d Seconds" %(totalhour,totalminute,totalsecond)

*注释:按照自己的需求更改上述代码中的数据库地址,用户,密码,库名,表名以及字段名等。

四、执行迁移脚本:

[root ~]#python nmytomongo.py &> /tmp/migratelog.txt &

脚本执行完成后查看/tmp/migratelog.txt数据迁移消耗的时间。

相关文章

在Python中输入一个以空格为间隔的数组方法

很多时候要从键盘连续输入一个数组,并用空格隔开,Python中的实现方法如下: >>> str_in = input('请以空格为间隔连续输入一个数组:') 然后...

pygame游戏之旅 游戏中添加显示文字

pygame游戏之旅 游戏中添加显示文字

本文为大家分享了pygame游戏之旅的第5篇,供大家参考,具体内容如下 在游戏中添加显示文字: 这里自己定义一个crash函数接口: def crash(): message_di...

Python实现屏幕截图的代码及函数详解

废话不多说,先给大家看下python实现屏幕截图的代码,具体代码如下所述: from selenium import webdriver import time def captur...

详解Python3注释知识点

Python3 注释 确保对模块, 函数, 方法和行内注释使用正确的风格 Python中的注释有单行注释和多行注释: Python中单行注释以 # 开头,例如:: # 这是一个...

Python实现把utf-8格式的文件转换成gbk格式的文件

需求:将utf-8格式的文件转换成gbk格式的文件 实现代码如下: 复制代码 代码如下: def ReadFile(filePath,encoding="utf-8"):  &...