实现两个主机间mysql数据同步
import pymysql
import pandas as pd
from sqlalchemy import create_engine
HOST_SUBOR_SYNCLIST = ('account_t', 'measure_system_t') # 需要更新的数据表
def syncSqldata(source_db, target_db):
for table in HOST_SUBOR_SYNCLIST :
query = "SELECT * FROM " + table
df = pd.read_sql(query, source_db) # 查询对应表中数据
df.to_sql(name=table, con=target_db, if_exists='replace', index=False)
if __name__ == '__main__':
source_db = pymysql.connect(
host="127.0.0.1",
user="root",
password="298453",
database="ns365"
)# 本地mysql配置
target_db = create_engine('mysql+pymysql://root:@192.168.0.141/ns365?charset=utf8mb4')# 目标mysql配置
# 这里目标mysql配置必须是create_engine创建,如果用connect()方式那么会报如下错误
# pandas.errors.DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': not all arguments converted during string formatting
syncSqldata(source_db, target_db)
如果报
pymysql.err.OperationalError: (2003, “Can’t connect to MySQL server on ‘192.168.0.141’ (timed out)”)
那么很大可能是目标mysql不允许远程连接
执行如下命令即可