python实现数据库跨服务器迁移


Posted in Python onApril 12, 2018

 基于Python2.7的版本环境,Python实现的数据库跨服务器(跨库)迁移, 每以5000条一查询一提交,代码中可以自行更改每次查询提交数目.

# -*- coding: utf-8 -*-

import MySQLdb
import time
import warnings

warnings.filterwarnings("ignore")


class ConnectMysql(object):
  def __init__(self):
#     这里设置分页查询, 每页查询多少数据
    self.page_size = 5000

  def getTable(self):
    conn = MySQLdb.connect(
      host="***.***.**.**",
      user="****",
      passwd="*************",
      db='****',
      charset='utf8'
    )
    conn_local = MySQLdb.connect(
      host="********************************",
      user="**********",
      passwd="********",
      db='*******',
      charset='utf8'
    )
    cur = conn.cursor()
    cur_local = conn_local.cursor()
    cur.execute('show tables')
    tables = cur.fetchall()
    for table in tables:
      print str(table[0]).lower()
      # 需要迁移的数据库查询表的列数
      cur.execute("SELECT COUNT(*) FROM information_schema.COLUMNS WHERE table_schema='china' AND table_name='" + table[0] + "'")
      table_col_count = cur.fetchone()
      # print table_col_count[0]
      # 需要迁移的数据库查询表的结构
      cur.execute('show create table ' + table[0])
      result = cur.fetchall()
      create_sql = result[0][1]
      # 查询需要迁移的数据库表的数据条数
      cur.execute('select count(*) from ' + table[0])
      total = cur.fetchone()
      page = total[0] / self.page_size
      page1 = total[0] % self.page_size
      if page1 != 0:
        page = page + 1

      # 阿里云数据库创建表
      cur_local.execute("SELECT table_name FROM information_schema.`TABLES` WHERE table_schema='user' AND table_name='" + str(table[0]).lower() + "'")
      table_name = cur_local.fetchone()
      if table_name is None:
        cur_local.execute(create_sql)
      for p in range(0, page):
        while True:
          try:
            print '开始', table[0], '的第', p + 1, '页查询'
            if p == 0:
              limit_param = ' limit ' + str(p * self.page_size) + ',' + str(self.page_size)
            else:
              limit_param = ' limit ' + str(p * self.page_size + 1) + ',' + str(self.page_size)
            cur.execute('select * from ' + table[0] + limit_param)
            inserts = cur.fetchall()
            print '查询成功'
            param = ''
            for i in range(0, table_col_count[0]):
              param = param + '%s,'
            print '开始插入'
            cur_local.executemany('replace into ' + table[0] + ' values (' + param[0:-1] + ')', inserts)
            print table[0], '的第', p + 1, '页, 插入完成, 还有', page - p - 1, '页, 任重而道远'
            conn_local.commit()
            break
          except Exception as e:
            print e
            time.sleep(60)
            cur = conn.cursor()
            cur_local = conn_local.cursor()
        print table[0], ' 插入完成'
        print '\n \n ======================================================================== \n\n'
    cur_local.close()
    conn_local.close()
    cur.close()
    conn.close()


if __name__ == '__main__':
  conn_mysql = ConnectMysql()
  conn_mysql.getTable()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python实现倒计时的示例
Feb 14 Python
Python虚拟环境项目实例
Nov 20 Python
Python tkinter label 更新方法
Oct 11 Python
使用django-guardian实现django-admin的行级权限控制的方法
Oct 30 Python
用python爬取租房网站信息的代码
Dec 14 Python
WxPython建立批量录入框窗口
Feb 27 Python
浅析Python与Mongodb数据库之间的操作方法
Jul 01 Python
django中related_name的用法说明
May 20 Python
python脚本和网页有何区别
Jul 02 Python
Python数据可视化实现漏斗图过程图解
Jul 20 Python
Python激活Anaconda环境变量的详细步骤
Jun 08 Python
Python借助with语句实现代码段只执行有限次
Mar 23 Python
解决python3爬虫无法显示中文的问题
Apr 12 #Python
python读取中文txt文本的方法
Apr 12 #Python
基于python 处理中文路径的终极解决方法
Apr 12 #Python
解决Python2.7读写文件中的中文乱码问题
Apr 12 #Python
python 实现对文件夹内的文件排序编号
Apr 12 #Python
pandas数值计算与排序方法
Apr 12 #Python
python搭建服务器实现两个Android客户端间收发消息
Apr 12 #Python
You might like
PHP5 的对象赋值机制介绍
2011/08/02 PHP
php数组函数序列之sort() 对数组的元素值进行升序排序
2011/11/02 PHP
PHP实现AES256加密算法实例
2014/09/22 PHP
Yii2超好用的日期和时间组件(值得收藏)
2016/05/05 PHP
如何通过View::first使用Laravel Blade的动态模板详解
2017/09/21 PHP
tp5 实现列表数据根据状态排序
2019/10/18 PHP
Laravel框架实现即点即改功能的方法分析
2019/10/31 PHP
JavaScript 对Cookie 操作的封装小结
2009/12/31 Javascript
使用jquery为table动态添加行的实现代码
2011/03/30 Javascript
js substr、substring和slice使用说明小记
2011/09/15 Javascript
input标签内容改变的触发事件介绍
2014/06/18 Javascript
基于NodeJS的前后端分离的思考与实践(二)模版探索
2014/09/26 NodeJs
js实现ctrl+v粘贴上传图片(兼容chrome、firefox、ie11)
2016/03/09 Javascript
基于javascript编写简单日历
2016/05/02 Javascript
Bootstrap表单布局
2016/07/19 Javascript
Vue.js自定义指令的用法与实例解析
2017/01/18 Javascript
Vue2.0仿饿了么webapp单页面应用详细步骤
2018/07/08 Javascript
微信小程序导航栏滑动定位功能示例(实现CSS3的positionsticky效果)
2019/01/24 Javascript
详解Vue-cli3.X使用px2rem遇到的问题
2019/08/09 Javascript
JavaScript this使用方法图解
2020/02/04 Javascript
如何封装Vue Element的table表格组件
2021/02/06 Vue.js
Python实现的json文件读取及中文乱码显示问题解决方法
2018/08/06 Python
python模糊图片过滤的方法
2018/12/14 Python
使用urllib库的urlretrieve()方法下载网络文件到本地的方法
2018/12/19 Python
使用python实现希尔、计数、基数基础排序的代码
2019/12/25 Python
Python Numpy 控制台完全输出ndarray的实现
2020/02/19 Python
总结Pyinstaller的坑及终极解决方法(小结)
2020/09/21 Python
美国班级戒指、帽子和礼服、毕业产品、年鉴:Balfour
2018/11/01 全球购物
意大利独特而优质的家居用品:Fazzini
2018/12/05 全球购物
SIDESTEP荷兰:在线购买鞋子
2019/11/18 全球购物
德尔福集团DELPHI的笔试题
2012/02/22 面试题
买房子个人收入证明
2014/01/16 职场文书
运动会解说词100字
2014/01/31 职场文书
2015年派出所民警工作总结
2015/04/24 职场文书
加薪通知
2015/04/25 职场文书
2015年小学体育工作总结
2015/05/22 职场文书