python制作mysql数据迁移脚本


Posted in Python onJanuary 01, 2019

用python写了个数据迁移脚本,主要是利用从库将大的静态表导出表空间,载导入到目标实例中。

#!/usr/bin/env python3
#-*- coding:utf8 -*-
#author:zhanbin.liu
#!!!!!DB必须同版本
#python3环境  pip3 install pymysql paramiko

import os
#from pathlib import Path
import sys
import pymysql
import paramiko

#每次只能迁移一个DB下的表,到指定DB
#GRANT SELECT, CREATE, RELOAD, ALTER, LOCK TABLES ON *.* TO 'data_migration'@'192.168.%' IDENTIFIED BY 'data_migration@123';
tables='sqlauto_cluster,sqlauto_user'    #以,分割的字符串,如a,b,c
tableList = tables.split(',')
sourceIp = '192.168.1.101'
sourceDataBase = '/data/mysql/3306/data'
sourceDbName = 'inception_web'
sourceDataDir = os.path.join(sourceDataBase,sourceDbName)
desIp = '192.168.1.102'
desDataBase = '/data/mysql/3306/data'
desDbName = 'inception_web'
desDataDir = os.path.join(desDataBase,desDbName)

# for table in tableList:
#   desFile = Path("%s/%s.ibd" %(desDataDir,table))
#   print(desFile)
#   if desFile.is_file():
#     print("ok")
#   else:
#     print("no")

comUser = 'data_migration'
comPwd = 'data_migration@123'
comPort = 3306

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

def table_judge():
  print("table_judge")
  sourceTableExist = pymysql.connect(sourceIp,comUser,comPwd,sourceDbName,comPort,charset='utf8')
  desTableExist = pymysql.connect(desIp,comUser,comPwd,desDbName,comPort,charset='utf8')
  sourceTables = []
  desTables = []
  cursor_source = sourceTableExist.cursor()
  cursor_des = desTableExist.cursor()

  for table in tableList:
    #print(table)
    cursor_source.execute("select TABLE_NAME from information_schema.TABLES where TABLE_SCHEMA='%s' and TABLE_NAME='%s';" % (sourceDbName,table))
    sourceTable_tmp = cursor_source.fetchall()
    cursor_des.execute("select TABLE_NAME from information_schema.TABLES where TABLE_SCHEMA='%s' and TABLE_NAME='%s';" % (desDbName,table))
    desTable_tmp = cursor_des.fetchall()
    #print(desTable_tmp)
    if sourceTable_tmp is ():
      sourceTables.append(table)
    if desTable_tmp is not ():
      desTables.append(desTable_tmp[0][0])
  sourceTableExist.close()
  desTableExist.close()

  s=d=0
  if sourceTables != []:
    print('迁移源不存在将要迁移的表:',sourceIp,sourceDbName, sourceTables,' 请检查')
    s=1
  if desTables != []:
    print('目标库存在将要迁移的表:',desIp,desDbName,desTables,' 请移除')
    d=1
  if s == 1 or d == 1:
    sys.exit()

def data_sync():
  print('data_sync')
  db_source = pymysql.connect(sourceIp,comUser,comPwd,sourceDbName,comPort,charset='utf8')
  db_des = pymysql.connect(desIp,comUser,comPwd,desDbName,comPort,charset='utf8')
  cursor_db_source = db_source.cursor()
  cursor_db_des = db_des.cursor()

  for table in tableList:
    print("正在同步表:",table)
    cursor_db_source.execute("show create table %s;" % (table))
    createTableSQL = cursor_db_source.fetchall()[0][1]
    print(createTableSQL)
    try:
      cursor_db_des.execute(createTableSQL)
    except Exception as error:
      print(error)
    cursor_db_source.execute("flush table %s with read lock;" % (table))
    cursor_db_des.execute("alter table %s discard tablespace;" % (table))

    client.connect(sourceIp, 22, 'root')
    stdin1, stdout1, stderr1 = client.exec_command("scp %s %s:%s " % (sourceDataDir+"/"+table+".ibd", desIp, desDataDir))
    stdin2, stdout2, stderr2 = client.exec_command("scp %s %s:%s " % (sourceDataDir+"/"+table+".cfg", desIp, desDataDir))
    a_e_1 = stderr1.readlines()
    a_e_2 = stderr2.readlines()
    if a_e_1 != [] or a_e_2 != []:
      print(a_e_1,a_e_2)
      sys.exit()
    client.close()

    client.connect(desIp, 22, 'root')
    stdin3, stdout3, stderr3 = client.exec_command("chown -R mysql.mysql %s*" % (desDataDir+"/"+table))
    a_e_3 = stderr3.readlines()
    if a_e_3 != []:
      print(a_e_1, a_e_2)
      sys.exit()
    client.close()
    #cursor_db_source.execute("select sleep(10);")
    cursor_db_source.execute("unlock tables;")
    cursor_db_des.execute("alter table %s import tablespace;" % (table))
    print("同步完成")

  cursor_db_source.close()
  cursor_db_des.close()

def data_checksum():
  print('data_checksum')
  db_source = pymysql.connect(sourceIp,comUser,comPwd,sourceDbName,comPort,charset='utf8')
  db_des = pymysql.connect(desIp,comUser,comPwd,desDbName,comPort,charset='utf8')
  cursor_db_source = db_source.cursor()
  cursor_db_des = db_des.cursor()

  for table in tableList:
    print("正在校验表:", table)
    cursor_db_source.execute("checksum table %s;" % (table))
    ck_s = cursor_db_source.fetchall()[0][1]
    cursor_db_des.execute("checksum table %s;" % (table))
    ck_d = cursor_db_des.fetchall()[0][1]
    if ck_s != ck_d:
      print("表不一致:",table)
    else:
      print("表一致:",table)

  cursor_db_source.close()
  cursor_db_des.close()

if __name__ == "__main__":
  table_judge()
  data_sync()
  data_checksum()
  print('haha')
Python 相关文章推荐
利用python生成一个导出数据库的bat脚本文件的方法
Dec 30 Python
Django REST为文件属性输出完整URL的方法
Dec 18 Python
python实现日常记账本小程序
Mar 10 Python
对Python中列表和数组的赋值,浅拷贝和深拷贝的实例讲解
Jun 28 Python
Python wxPython库消息对话框MessageDialog用法示例
Sep 03 Python
解决pandas .to_excel不覆盖已有sheet的问题
Dec 10 Python
Python实现的序列化和反序列化二叉树算法示例
Mar 02 Python
Pycharm 文件更改目录后,执行路径未更新的解决方法
Jul 19 Python
基于Python实现签到脚本过程解析
Oct 25 Python
python实现Pyecharts实现动态地图(Map、Geo)
Mar 25 Python
如何在python中处理配置文件代码实例
Sep 27 Python
使用Python通过企业微信应用给企业成员发消息
Apr 18 Python
在python中将字符串转为json对象并取值的方法
Dec 31 #Python
对python中Json与object转化的方法详解
Dec 31 #Python
python使用zip将list转为json的方法
Dec 31 #Python
python 获取utc时间转化为本地时间的方法
Dec 31 #Python
python 实现UTC时间加减的方法
Dec 31 #Python
Python从单元素字典中获取key和value的实例
Dec 31 #Python
对Python 两大环境管理神器 pyenv 和 virtualenv详解
Dec 31 #Python
You might like
德劲1104的电路分析与改良
2021/03/01 无线电
不用数据库的多用户文件自由上传投票系统(1)
2006/10/09 PHP
PHP连接MongoDB示例代码
2012/09/06 PHP
PHP中__get()和__set()的用法实例详解
2013/06/04 PHP
PHP中定义数组常量(array常量)的方法
2014/11/17 PHP
PHP中is_file()函数使用指南
2015/05/08 PHP
php获取flash尺寸详细数据的方法
2016/11/12 PHP
Laravel5.4框架使用socialite实现github登录的方法
2019/03/20 PHP
ext 同步和异步示例代码
2009/09/18 Javascript
使用Json比用string返回数据更友好,也更面向对象一些
2011/09/13 Javascript
js动态添加表格数据使用insertRow和insertCell实现
2014/05/22 Javascript
判断浏览器的内核及版本号方法汇总
2015/01/05 Javascript
深入学习JavaScript的AngularJS框架中指令的使用方法
2016/03/05 Javascript
简单实现Bootstrap标签页
2020/08/09 Javascript
Vue.js仿Metronic高级表格(二)数据渲染
2017/04/19 Javascript
详解vue静态资源打包中的坑与解决方案
2018/02/05 Javascript
webuploader分片上传的实现代码(前后端分离)
2018/09/10 Javascript
layui使用数据表格实现购物车功能
2019/07/26 Javascript
解决vue的过渡动画无法正常实现问题
2019/10/31 Javascript
详解Webpack4多页应用打包方案
2020/07/16 Javascript
vue-amap根据地址回显地图并mark的操作
2020/11/03 Javascript
python实现批量下载新浪博客的方法
2015/06/15 Python
Python随手笔记之标准类型内建函数
2015/12/02 Python
Python构造自定义方法来美化字典结构输出的示例
2016/06/16 Python
Python scikit-learn 做线性回归的示例代码
2017/11/01 Python
python 删除指定时间间隔之前的文件实例
2018/04/24 Python
Python常用模块logging——日志输出功能(示例代码)
2019/11/20 Python
Python字符串、列表、元组、字典、集合的补充实例详解
2019/12/20 Python
python解析多层json操作示例
2019/12/30 Python
La Senza官网:北美顶尖性感内衣品牌
2018/08/03 全球购物
美术师范毕业生自荐信
2013/11/16 职场文书
一月红领巾广播稿
2014/02/11 职场文书
面试必备的求职信
2014/05/25 职场文书
小学生国庆演讲稿
2014/09/05 职场文书
关于运动会的广播稿
2014/09/22 职场文书
区长工作作风个人整改措施
2014/10/01 职场文书