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编程中函数的使用要点
Mar 20 Python
Bottle框架中的装饰器类和描述符应用详解
Oct 28 Python
用python制作游戏外挂
Jan 04 Python
python对离散变量的one-hot编码方法
Jul 11 Python
python实现汉诺塔算法
Mar 01 Python
Python判断以什么结尾以什么开头的实例
Oct 27 Python
对python多线程与global变量详解
Nov 09 Python
在pandas多重索引multiIndex中选定指定索引的行方法
Nov 16 Python
Python后台开发Django的教程详解(启动)
Apr 08 Python
Python API自动化框架总结
Nov 12 Python
记录模型训练时loss值的变化情况
Jun 16 Python
Python爬虫之用Xpath获取关键标签实现自动评论盖楼抽奖(二)
Jun 07 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
PHP编程网上资源导航
2006/10/09 PHP
php addslashes和mysql_real_escape_string
2010/01/24 PHP
php中static静态变量的使用方法详解
2010/06/04 PHP
PHP jQuery表单,带验证具体实现方法
2014/02/15 PHP
浅谈Coreseek、Sphinx-for-chinaese、Sphinx+Scws的区别
2016/12/15 PHP
PHP排序算法之直接插入排序(Straight Insertion Sort)实例分析
2018/04/20 PHP
jQuery Ajax 全解析
2009/02/08 Javascript
jQuery 遍历-nextUntil()方法以及prevUntil()方法的使用介绍
2013/04/26 Javascript
jQuery+AJAX实现无刷新下拉加载更多
2015/07/03 Javascript
jQuery实现HTML表格单元格的合并功能
2016/04/06 Javascript
AngularJS入门之动画
2016/07/27 Javascript
JavaScript职责链模式概述
2016/09/17 Javascript
利用jquery获取select下拉框的值
2016/11/23 Javascript
JS中Array数组学习总结
2017/01/18 Javascript
Thinkjs3新手入门之如何使用静态资源目录
2017/12/06 Javascript
微信小程序HTTP接口请求封装代码实例
2019/09/05 Javascript
微信小程序实现列表滚动头部吸顶的示例代码
2020/07/12 Javascript
JavaScript实现多球运动效果
2020/09/07 Javascript
Vue+Element-U实现分页显示效果
2020/11/15 Javascript
Python实现的几个常用排序算法实例
2014/06/16 Python
python计算对角线有理函数插值的方法
2015/05/07 Python
深入解析Python中的list列表及其切片和迭代操作
2016/03/13 Python
解决Python网页爬虫之中文乱码问题
2018/05/11 Python
利用pandas读取中文数据集的方法
2018/07/25 Python
Python实例方法、类方法、静态方法的区别与作用详解
2019/03/25 Python
Docker部署Python爬虫项目的方法步骤
2020/01/19 Python
Python matplotlib读取excel数据并用for循环画多个子图subplot操作
2020/07/14 Python
用60行代码实现Python自动抢微信红包
2021/02/04 Python
中学家长会邀请函
2014/01/17 职场文书
安全生产责任书范本
2014/04/15 职场文书
十佳少先队员演讲稿
2014/09/12 职场文书
党的群众路线教育实践活动个人对照检查材料(教师)
2014/11/04 职场文书
2014年体育教学工作总结
2014/12/09 职场文书
2014年办公室文秘工作总结
2014/12/09 职场文书
员工试用期转正自我评价
2015/03/10 职场文书
80后创业总结的9条职场用人思想,记得收藏
2019/08/13 职场文书