如何修复操作错误:数据库已锁定?

问题描述 投票:0回答:1

我已经使用 SQLAlchemy 设置了到 SQLite 的数据库连接:

DATABASE = 'sqlite:////someaddress.db'
db = create_engine(DATABASE, echo=True, connect_args={'timeout': 15})
engine = db.raw_connection()

我的脚本轮询数据库:

POSTCODES = pd.read_sql("SELECT pcd, pcd2, pcds, LAT, LONG FROM postcodes", engine)

这样做没有问题。但当我尝试时:

self.df.to_sql(name='vouchers', con=engine, if_exists='replace', index=False)

我收到此错误:

操作错误:数据库已锁定

如何解决此错误?

pandas sqlite sqlalchemy
1个回答
0
投票

可能最容易使用上下文管理器。您不想永远保持连接,因此连接然后让上下文管理器关闭连接。

我认为 SQLAlchemy 希望您在传递 SQL 语句时将其包含在

text()
中。使用与内容匹配的变量名;
engine
表示
Engine()
conn
connection
表示
Connection()

#...
from sqlalchemy.sql import text

DATABASE = 'sqlite:////someaddress.db'
engine = create_engine(DATABASE, echo=True, connect_args={'timeout': 15})

# No commit, just reading, after context manager ends the connection is returned to the pool.
with engine.connect() as conn:
    POSTCODES = pd.read_sql(text("SELECT pcd, pcd2, pcds, LAT, LONG FROM postcodes"), conn)

# Commit after writing, after context manager ends the connection is returned to the pool.
with engine.connect() as conn:
    self.df.to_sql(name='vouchers', con=conn, if_exists='replace', index=False)
    conn.commit()

连接文档

© www.soinside.com 2019 - 2024. All rights reserved.