python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python Mysql数据同步

Python实现Mysql全量数据同步的脚本分享

作者:一夜奈何梁山

这篇文章主要为大家详细介绍了基于Python如何实现Mysql全量数据同步的功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起了解一下

一: 需求

线上数据全量同步到测试环境。

二:脚本

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import time
import datetime
import pymysql
import os

CUR_PATH = os.path.dirname(os.path.abspath(__file__))

# 需要同步的表
table_names = ['table_name_1', 'table_name_2']

source_db_config = {
    'db_host': 'XXXXX',
    'db_user': 'XXXX',
    'db_pwd': 'XXXX',
    'db': 'XCXXXCX',
    'db_port': 3306,
}

out_db_config = {
    'db_host': 'XXXX',
    'db_user': 'XXXX',
    'db_pwd': 'XXXX',
    'db': 'XXXXX',
    'db_port': 3306,
}


def get_datas(table_name):
    """源数据库,获取全量数据"""
    db = pymysql.connect(source_db_config['db_host'], source_db_config['db_user'], source_db_config['db_pwd'],
                         source_db_config['db'], source_db_config['dp_port'], charset='utf8')
    cursor = db.cursor(pymysql.cursors.DictCursor)
    readsql = '''select * from {}'''.format(table_name)
    cursor.execute(readsql)
    results = cursor.fetchall()
    for data in results:
        yield data
    cursor.close()
    db.close()


def format_data(data):
    """数据格式化"""
    for k, v in data.items():
        if type(v) == datetime.datetime:
            data[k] = "'{}'".format(v.strftime('%Y-%m-%d %H:%M:%S'))
        elif type(v) == type(v) == datetime.date:
            data[k] = "'{}'".format(v.strftime('%Y-%m-%d'))
        elif type(v) == unicode:
            data[k] = "'{}'".format(v.encode('utf-8'))
    return data


def out_put_data(table_name):
    write = pymysql.connect(out_db_config['db_host'], out_db_config['db_user'], out_db_config['db_pwd'],
                            out_db_config['db'], out_db_config['dp_port'], charset='utf8')
    for data in get_datas(table_name):
        write_cursor = write.cursor()
        data = format_data(data)
        sql = ','.join(['{}=%s'.format(item) for item in data.keys()])
        temp = sql % (tuple(data.values()))

        write_sql = '''insert  into  %s set %s on  duplicate key update %s''' % (table_name, temp, temp)
        try:
            write_cursor.execute(write_sql)
            write.commit()
        except Exception as e:
            print("insert error, err_msg is {}".format(e))
            write.rollback()
        finally:
            write_cursor.close()
    write.close()


if __name__ == "__main__":
    start_time = time.time()
    for table_name in table_names:
        out_put_data(table_name=table_name)
    end_time = time.time()
    cost_time = end_time - start_time
    print("cost_time is {}".format(cost_time))

到此这篇关于Python实现Mysql全量数据同步的脚本分享的文章就介绍到这了,更多相关Python Mysql数据同步内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文