• 技术文章 >Python技术 >Python基础教程

    python如何转移数据库里的数据

    小妮浅浅小妮浅浅2021-06-10 09:35:56原创3700

    1、常见数据库

    (1)Scikit-learn:需要复盖特征工程、模型训练和模型测试所有功能的程序库,Scikit-learn是最好的选择。这个优秀的免费软件可以提供机器学习和数据挖掘所需的所有工具,现在是python机器学习的标准库,建议使用成熟的机器学习算法。

    (2)NLTK:虽然不是机器学习的程序库,但它是自然语言处理所必需的库。除了文本处理功能之外,它还包括聚类、分词、词干提取、标记、分析等大量数据集和其他关于词法的资源。

    2、转移数据

    基于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学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 2.7,DELL G3电脑。

    专题推荐:python 数据库
    品易云
    上一篇:python代码提速有哪些方法 下一篇:python字符串如何取值

    相关文章推荐

    • MongoDB数据库删除文档的三种方法• flask中如何对数据库进行管理• python连接mysql数据库步骤

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网