import pymysql
def sync_students(source_db, target_db):
# 连接源数据库
source_conn = pymysql.connect(host=source_db['host'], user=source_db['user'], password=source_db['password'], database=source_db['database'])
source_cursor = source_conn.cursor()
# 连接目标数据库
target_conn = pymysql.connect(host=target_db['host'], user=target_db['user'], password=target_db['password'], database=target_db['database'])
target_cursor = target_conn.cursor()
# 查询源数据库的学生信息
source_cursor.execute("SELECT * FROM students")
rows = source_cursor.fetchall()
# 同步到目标数据库
for row in rows:
student_id, name, age, major = row
target_cursor.execute("INSERT INTO students (student_id, name, age, major) VALUES (%s, %s, %s, %s) ON DUPLICATE KEY UPDATE name=%s, age=%s, major=%s",
(student_id, name, age, major, name, age, major))
# 提交事务并关闭连接
target_conn.commit()
source_cursor.close()
target_cursor.close()
source_conn.close()
target_conn.close()
# 示例调用
source_db_config = {'host': 'localhost', 'user': 'root', 'password': 'password', 'database': 'source_db'}
target_db_config = {'host': 'localhost', 'user': 'root', 'password': 'password', 'database': 'target_db'}
sync_students(source_db_config, target_db_config)
]]>