sqlalchemy在sqlite中使用多个SQL语句执行脚本文件
我正在使用SQLalchemy连接到SQLite数据库。我想执行一些文件,script.sql
,其中包含多个 sql语句。
以前,我正在使用sqlite3
库并运行
with sqlite3.connect('my_database.db') as conn:
with open('script.sql') as s:
conn.executescript(s.read())
移动到sqlalchemy
,我发现这个问题,我从中使用session
实例编写了新代码:
session.execute(text(s.read())
但是,这返回错误,因为我的脚本包含多个语句。
sqlite3.Warning: You can only execute one statement at a time.
使用sqlalchemy
执行大型脚本文件的最佳方法是什么?
I'm using SQLAlchemy to connect to a SQLite database. I would like to execute some file, script.sql
, which contains multiple SQL statements.
Previously, I was using the sqlite3
library and running
with sqlite3.connect('my_database.db') as conn:
with open('script.sql') as s:
conn.executescript(s.read())
Moving to SQLAlchemy
, I found this question, from which I wrote new code using a session
instance:
session.execute(text(s.read())
However, this returns an error, because my script contains multiple statements.
sqlite3.Warning: You can only execute one statement at a time.
What is the best way to execute a large script file with multiple statements using SQLAlchemy
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Sqlalchemy本身仅调用光标的
execute
方法,该方法不支持执行多个语句。但是,可以直接访问DB API连接,并调用其executescript
方法:SQLAlchemy itself only calls the cursor's
execute
method, which does not support executing multiple statements. However it's possible to access the DB API connection directly, and call itsexecutescript
method:这是因为SQLite3仅支持一次执行一个语句。如果要执行多个语句,则需要单独命令。例如,
这将迭代一系列语句,然后依次执行每个语句。
This is because sqlite3 only supports executing one statement at a time. If you want to execute multiple statements, they need to be separate commands. For example,
This will iterate over the array of statements and execute each one in turn.