如何通过Python Connector加速MySQL大数据库导入速度?
大型MySQL数据库导入提速方案
我编写Python脚本导入大型MySQL数据库时,使用os.system调用mysql命令可正常执行,但导入速度极慢。根据资料,导入前设置autocommit=0、unique_checks=0、foreign_key_checks=0能大幅提升导入速度,但这些参数仅对当前数据库连接生效。我尝试了两种方法均未成功:
无效方法1:在os.system命令中添加SET语句
尝试将SET语句与mysql命令用分号拼接,结果执行到第一个分号就停止,无法完成后续操作:
importdb = "mysql -h " + DB_HOST + " -u " + DB_USER + " -p" + shlex.quote(DB_USER_PASSWORD)+ "; " + "use " + DB_TARGET + "; SET autocommit=0; SET unique_checks=0; SET FOREIGN_KEY_CHECKS=0; " + "source" + os.getcwd() + "\AllPrintings.sql; SET autocommit=1; SET unique_checks=1; SET FOREIGN_KEY_CHECKS=1;" os.system(importdb)
无效方法2:使用mysql.connector执行SET命令后导入
先通过mysql.connector执行参数设置语句,再尝试导入SQL文件,但无法完成导入操作:
cur.execute(f"SET autocommit=0;") cur.execute(f"SET unique_checks=0;") cur.execute(f"SET FOREIGN_KEY_CHECKS=0;") cur.execute(DB_TARGET + ' < ' + os.getcwd() + '\AllPrintings.sql') conn.commit() cur.execute(f"SET autocommit=1;") cur.execute(f"SET unique_checks=1;") cur.execute(f"SET FOREIGN_KEY_CHECKS=1;");
最终有效解决方案
通过修改SQL文件本身,在文件开头添加参数设置语句,结尾恢复参数设置,测试后导入时间从73分钟缩短至2分钟:
# 初始导入代码(仅作参考) importdb = "mysql -h " + DB_HOST + " -u " + DB_USER + " -p" + shlex.quote(DB_USER_PASSWORD) + " " + DB_TARGET + " < " + os.getcwd() + "\AllPrintings.sql" os.system(importdb) # 修改SQL文件的代码 with open(os.getcwd() + "\AllPrintings.sql", "r+",encoding="utf8") as f: content = f.read() f.seek(0, 0) f.write("SET autocommit=0;\nSET unique_checks=0;\nSET FOREIGN_KEY_CHECKS=0;" + '\n' + content) with open(os.getcwd() + "\AllPrintings.sql", "a+", encoding="utf8") as f: f.write("\nSET unique_checks=1;\nSET FOREIGN_KEY_CHECKS=1;\n")
内容的提问来源于stack exchange,提问作者Starid
相关产品推荐
相关产品推荐

