Python 调用 mysql 能否一次执行多条语句

2022-12-08 11:57:59 +08:00
 milkpuff

现有一文件,其中存储大量 sql 语句,操作多个表,需要 python 读取并执行。

使用 mysqlclient 库,似乎只能一次执行一条语句,执行 100 条语句需要 100 次网络通信;

如果将语句用分号连接,调用 cursor.execute 会报:

MySQLdb._exceptions.ProgrammingError: (2014, "Commands out of sync; you can't run this command now")

cursor.executemany 方法只能对同一个表进行插入,不适用多表的情形。并且查看 executemany 的源码发现也是逐条请求的。

请问,一次网络请求执行多条 sql 语句,能否实现?

1176 次点击
所在节点    数据库
2 条回复
westoy
2022-12-08 12:02:32 +08:00
execute 加个 multi=True 试试
sarices
2022-12-08 12:07:42 +08:00
`
# read the file containing the SQL statements
with open('sql_statements.txt', 'r') as f:
sql = f.read()

# create a cursor and execute the SQL statements
cursor = conn.cursor()
cursor.executescript(sql)

`

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/901030

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX