首页 > Linux操作系统 > Linux操作系统 > 用python进行数据库数据迁移
import MySQLdb
import psycopg2
#创建mysql连接,通过cursor获取游标,用execute获取查询结果
conn=MySQLdb.connect(host='192.168.129.15',port=3306,user='root',passwd='123456') cursor1=conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) cursor1.execute("select id,name from test.fader where id=1") rows=cursor1.fetchall()
#如果sql语句很长影响脚本的排版时,可以将sql写到文件中,通过读取文件执行。#file=open("/root/python/root/python/update_home_data.txt") #sql=file.read() #cursor1.execute("%s"%(sql)) #file.close() #rows=cursor1.fetchall()
#创建pg连接,通过cursor获取游标,先清空目标表
conn2 = psycopg2.connect(database="edw", user="gpadmin", password="123456", host="172.30.248.10", port="5432")
cursor2 = conn2.cursor()
cursor2.execute("truncate work_test.fader")
#循环mysql中获取的结果,并插入到pg中
for list in rows: id=list['id'] name=list['name'] cursor2.execute("insert into work_test.fader(id,name) values('%s','%s') "%(id,name)) cursor1.close() cursor2.close() conn.commit() conn2.commit() conn.close() conn2.close()
再使用crontab每5秒执行一次注:这种方法只适合小数量的跨库数据准实时传输,因为插入的时候是一条一条的插入,不是批量插入会有大量的commit操作。如果数据量大会对关系型数据库的性能有影响(这和关系型数据库操作日志缓存落盘机制有关,在这里就不过多阐述)
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29989552/viewspace-2130801/ ,如需转载,请注明出处,否则将追究法律责任。