简体   繁体   English

如何使用 pymysql 运行批量插入查询?

[英]How can I run bulk insert query using pymysql?

How can I run insert query script file using pymysql?如何使用 pymysql 运行插入查询脚本文件?

I made a insert query script file for big data.我为大数据制作了一个插入查询脚本文件。 (data row count: 50,000) (数据行数:50,000)

The file name is bulkinsert.sql and it contains query like below.文件名是bulkinsert.sql,它包含如下查询。

INSERT INTO test( dt, user, usertype, ip) VALUES 
("2016-05-01", 3103945, , 1, "175.195.249.217"), 
("2016-05-01", 3103946, , 1, "175.195.249.218"), 
("2016-05-01", 3103947, , 1, "175.195.249.219"), 
................
................
................
("2016-05-01", 3104000, , 1, "175.195.249.500");

I used pymysql, but I can't find a way to insert or run sql file directly.我用的是pymysql,但是找不到直接插入或运行sql文件的方法。 Like below.像下面。

cursor.execute(bulkinsert.sql)

When I read their guide, I have to read the sql sentence and execute it.当我阅读他们的指南时,我必须阅读sql语句并执行它。 But my data row count is too many to read.但是我的数据行数太多而无法阅读。 Is their any way to import or run sql script in pymysql?他们有什么方法可以在 pymysql 中导入或运行 sql 脚本吗?

If you don't need the output of execution, maybe subprocess is an alternative approach.如果您不需要执行的输出,也许 subprocess 是一种替代方法。 PS: replace the Password keyword with your own. PS:将Password关键字替换为您自己的关键字。

from subprocess import Popen, PIPE
process = Popen(['mysql', db, '-u', user, '-pPassword'],
                stdout=PIPE, stdin=PIPE)
output = process.communicate('source ' + filename)[0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM