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图像常规操作
Nov 11 Python
python交互式图形编程实例(一)
Nov 17 Python
Python使用pyodbc访问数据库操作方法详解
Jul 05 Python
Ubuntu下Anaconda和Pycharm配置方法详解
Jun 14 Python
python简单实现矩阵的乘,加,转置和逆运算示例
Jul 10 Python
Numpy数组array和矩阵matrix转换方法
Aug 05 Python
tensorflow实现测试时读取任意指定的check point的网络参数
Jan 21 Python
python误差棒图errorbar()函数实例解析
Feb 11 Python
Python栈的实现方法示例【列表、单链表】
Feb 22 Python
python实现在内存中读写str和二进制数据代码
Apr 24 Python
python时间time模块处理大全
Oct 25 Python
如何基于Python和Flask编写Prometheus监控
Nov 25 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
超级简单的php+mysql留言本源码
2009/11/11 PHP
PHP根据传来的16进制颜色代码自动改变背景颜色
2014/06/13 PHP
TP5(thinkPHP框架)实现后台清除缓存功能示例
2019/05/29 PHP
PHP实现cookie跨域session共享的方法分析
2019/08/23 PHP
运用Windows XP附带的Msicuu.exe、Msizap.exe来彻底卸载顽固程序
2007/04/21 Javascript
jquery 操作iframe的几种方法总结
2013/12/13 Javascript
元素未显示设置width/height时IE中使用currentStyle获取为auto
2014/05/04 Javascript
jquery仿搜索自动联想功能代码
2014/05/23 Javascript
jQuery中parentsUntil()方法用法实例
2015/01/07 Javascript
JavaScript DOM事件(笔记)
2015/04/08 Javascript
使用递归遍历对象获得value值的实现方法
2016/06/14 Javascript
jQuery AJAX timeout 超时问题详解
2016/06/21 Javascript
jQuery中table数据的值拷贝和拆分
2017/03/19 Javascript
JavaScript实现百度搜索框效果
2020/03/26 Javascript
JavaScript中arguments和this对象用法分析
2018/08/08 Javascript
Vue检测屏幕变化来改变不同的charts样式实例
2020/10/26 Javascript
python集合类型用法分析
2015/04/08 Python
Python中的choice()方法使用详解
2015/05/15 Python
django框架中间件原理与用法详解
2019/12/10 Python
python 经典数字滤波实例
2019/12/16 Python
python GUI库图形界面开发之PyQt5计数器控件QSpinBox详细使用方法与实例
2020/02/28 Python
C#面试常见问题
2013/02/25 面试题
水利学院求职自荐书
2014/02/01 职场文书
护士个人自我鉴定
2014/03/24 职场文书
元宵晚会主持词
2014/03/25 职场文书
2014年五四青年节演讲比赛方案
2014/04/22 职场文书
超市仓管员岗位职责范本
2014/09/18 职场文书
2014年师德师风自我剖析材料
2014/09/27 职场文书
个人批评与自我批评
2014/10/15 职场文书
2015年幼儿园元旦游艺活动策划书
2014/12/09 职场文书
2014年高中教师工作总结
2014/12/19 职场文书
小学教师个人工作总结2015
2015/04/20 职场文书
2015年端午节活动方案
2015/05/05 职场文书
浅谈克隆 JavaScript
2021/11/02 Javascript
mysql sum(if())和count(if())的用法说明
2022/01/18 MySQL
Python安装使用Scrapy框架
2022/04/12 Python