对于新老系统大数据量迁移数据的预处理和表字段的映射以及表映射编写一个程序新系统的表有1000张 老系统的表有800张
由于题目中没有具体定义数据迁移的方式,下面提供一种简单的数据迁移方案,并给出程序的框架。
数据迁移方案:
- 首先对新老系统中的所有表进行对比,找出表名相同的表。
- 对于表名相同的表,通过表字段的对比,找出字段名相同的字段。
- 对于字段名相同的字段,将老系统中的数据通过SQL语句查询出来,然后通过SQL插入语句插入到新系统中。
- 对于新系统中不存在的表和字段,需要先创建表和字段,再进行数据迁移。
程序框架:
import pymysql
# 连接数据库
old_conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='password', db='old_db', charset='utf8')
new_conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='password', db='new_db', charset='utf8')
# 获取游标
old_cursor = old_conn.cursor()
new_cursor = new_conn.cursor()
# 获取老系统中的所有表名
old_cursor.execute("SHOW TABLES")
old_tables = old_cursor.fetchall()
old_table_names = [table[0] for table in old_tables]
# 获取新系统中的所有表名
new_cursor.execute("SHOW TABLES")
new_tables = new_cursor.fetchall()
new_table_names = [table[0] for table in new_tables]
# 对比新老系统中的表,找出表名相同的表
same_tables = set(old_table_names) & set(new_table_names)
# 遍历表名相同的表
for table_name in same_tables:
# 获取老系统中的所有字段名
old_cursor.execute("DESC "+table_name)
old_fields = old_cursor.fetchall()
old_field_names = [field[0] for field in old_fields]
# 获取新系统中的所有字段名
new_cursor.execute("DESC "+table_name)
new_fields = new_cursor.fetchall()
new_field_names = [field[0] for field in new_fields]
# 对比新老系统中的字段,找出字段名相同的字段
same_fields = set(old_field_names) & set(new_field_names)
# 生成SQL语句进行数据迁移
sql = "INSERT INTO "+table_name+" ("
for field_name in same_fields:
sql += field_name+","
sql = sql[:-1] + ") VALUES ("
for i in range(len(same_fields)):
sql += "%s,"
sql = sql[:-1] + ")"
# 查询老系统中的数据并插入到新系统中
old_cursor.execute("SELECT * FROM "+table_name)
old_data = old_cursor.fetchall()
for data in old_data:
new_cursor.execute(sql, data)
# 提交事务
new_conn.commit()
# 关闭游标和数据库连接
old_cursor.close()
new_cursor.close()
old_conn.close()
new_conn.close()
``
原文地址: https://www.cveoy.top/t/topic/eiRS 著作权归作者所有。请勿转载和采集!