SQLAlchemy - 无需编写/锁定数据库即可进行查询

时间:2017-04-12 22:49:08

标签: python multithreading sqlite permissions sqlalchemy

我有一个多线程数据分析管道,用于查询数据库(通过SQLAlchemy)。此外,通过同步来跨多个系统同步数据库 - 长话短说,这意味着无法始终保证写入权限。

即使我能够保证写入权限,我仍然偶尔也会随机地获得操作错误:

OperationalError: (sqlite3.OperationalError) database is locked

我用来加载查询会话的代码如下:

def loadSession(db_path):
    db_path = "sqlite:///" + path.expanduser(db_path)
    engine = create_engine(db_path, echo=False)
    Session = sessionmaker(bind=engine)
    session = Session()
    Base.metadata.create_all(engine)
    return session, engine

可以在完整的背景here中看到。

我的查询(以及我将其转换为值的方式)如下所示:

    session, engine = loadSession(db_path)
    sql_query=session.query(LaserStimulationProtocol).filter(LaserStimulationProtocol.code==stim_protocol_dictionary[scan_type])
    mystring = sql_query.statement
    mydf = pd.read_sql_query(mystring,engine)
    delay = int(mydf["stimulation_onset"][0])

同样,可以找到完整的上下文here

如何更改我的代码以便可以查询数据库而无需依赖文件可写/解锁?我检查了文件的校验和,并且在查询时不会改变,所以很明显我没有写任何东西。因此,我想应该有一些方法来提取我正在寻找的信息而无需写访问权?

1 个答案:

答案 0 :(得分:-1)

我写了一篇关于这个主题的博客文章,它提供了一些关于这个问题的更多解释以及解决它的一些方法:http://charlesleifer.com/blog/multi-threaded-sqlite-without-the-operationalerrors/

Peewee ORM有一个扩展,旨在支持多个线程写入SQLite数据库。 http://docs.peewee-orm.com/en/latest/peewee/playhouse.html#sqliteq

相关问题