Python MySQL数据迁移是指使用Python脚本将数据从一个MySQL数据库迁移到另一个MySQL数据库的过程。这个过程通常包括以下几个步骤:
以下是一个简单的Python脚本示例,用于将数据从一个MySQL数据库迁移到另一个MySQL数据库:
import mysql.connector
# 连接源数据库
source_db = mysql.connector.connect(
host="source_host",
user="source_user",
password="source_password",
database="source_database"
)
# 连接目标数据库
target_db = mysql.connector.connect(
host="target_host",
user="target_user",
password="target_password",
database="target_database"
)
# 创建游标
source_cursor = source_db.cursor()
target_cursor = target_db.cursor()
# 查询源数据库中的数据
source_cursor.execute("SELECT * FROM source_table")
rows = source_cursor.fetchall()
# 将数据插入目标数据库
for row in rows:
query = f"INSERT INTO target_table (column1, column2, column3) VALUES (%s, %s, %s)"
target_cursor.execute(query, row)
# 提交事务
target_db.commit()
# 关闭连接
source_cursor.close()
target_cursor.close()
source_db.close()
target_db.close()
通过以上步骤和方法,可以有效地进行Python MySQL数据迁移。
领取专属 10元无门槛券
手把手带您无忧上云