簡體   English   中英

SQLAlchemy 在 SQLite 中執行帶有多個 SQL 語句的腳本文件

[英]SQLAlchemy execute script file with multiple SQL statements in SQLite

我正在使用 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執行包含多個語句的大型腳本文件的最佳方法是什么?

SQLAlchemy 本身只調用游標的execute方法,不支持執行多條語句。 但是可以直接訪問 DB API 連接,並調用它的executescript方法:

import sqlalchemy as sa

engine = sa.create_engine('sqlite:///so72341960.db')

# Create a table for our example.
tbl = sa.Table(
    'mytable',
    sa.MetaData(),
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('name', sa.String),
)

# Ensure we start with a clean table.
tbl.drop(engine, checkfirst=True)
tbl.create(engine)

SQL = """
INSERT INTO mytable (name) VALUES ('Alice');
INSERT INTO mytable (name) VALUES ('Bob');
"""

with engine.begin() as conn:
    dbapi_conn = conn.connection
    dbapi_conn.executescript(SQL)

這是因為 sqlite3 一次只支持執行一條語句。 如果要執行多個語句,它們需要是單獨的命令。 例如,

statements = [] // put your statements in this array
for statement in statements:
  session.execute(text(statement))

這將遍歷語句數組並依次執行每個語句。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM