1. 程式人生 > >python將mysql表中資料抽取到另一個mysql庫中,持續更新抽取到oracle中

python將mysql表中資料抽取到另一個mysql庫中,持續更新抽取到oracle中

import MySQLdb
import ConfigParser
class Mysql2Mysql(object):
    def getConn(self,filename,dbname):
        cf = ConfigParser.ConfigParser()
        cf.read(filename)
        db_host=cf.get(dbname,'db_host')
        db_user=cf.get(dbname,'db_user')
        db_pass=cf.get(dbname,'db_pass')
        db_name= cf.get(dbname,'db_name')
        db_port= cf.get(dbname,'db_port')
        db_char=cf.get(dbname,'db_char')
        try:
            conn=MySQLdb.connect(host=db_host,port=int(db_port),user=db_user,passwd=db_pass,db=db_name)
            return conn
        except Exception as e:
            print str(e)
            return -1
    def closeDB(self,conn):
        try:
            if conn:
                conn.close()
        except Exception as e:
            print str(e)
    def insertMysql(self,conn,sql,list):
        cur=conn.cursor()
        cur.executemany(sql,list)
        conn.commit()
        cur.close()
        self.closeDB(conn)
    def getData(self,conn,sql):
        cur=conn.cursor()
        cur.execute(sql)
        result_set=cur.fetchall()
        return list(result_set)
    def insertData(self,conn,sql,data_list):
        cur=conn.cursor()
        cur.executemany(sql,data_list)
        conn.commit()
if __name__=="__main__":
    exportmysql=Mysql2Mysql()
    get_sql='select * from user_event'
    insert_sql='insert into user_event values(%s,%s,%s,%s)'
    src_conn=exportmysql.getConn('D:/UliPad/Pythoncode/extract/conf/db.ini','src_db')
    target_conn=exportmysql.getConn('D:/UliPad/Pythoncode/extract/conf/db.ini','target_db')
    list=exportmysql.getData(src_conn,get_sql)

    exportmysql.insertData(target_conn,insert_sql,list)

配置檔案內容如下:

[src_db]
db_port = 3306
db_user = root
db_host = 127.0.0.1
db_pass = ltl123
db_name = test
db_char = utf-8


[target_db]
db_port = 3306
db_user = root
db_host = 127.0.0.1
db_pass = ltl123
db_name = mysql
db_char = utf-8