如何使用SQLAlchemy设置SQLite PRAGMA语句

tom*_*omc 12 sqlite sqlalchemy

我希望SQLAlchemy将SQLite .journal文件放在内存中以加快性能.我试过这个:

sqlite_db_engine = create_engine('sqlite:///%s' % str(dbname), connect_args = {'PRAGMA     journal_mode':'MEMORY', 'PRAGMA synchronous':'OFF', 'PRAGMA temp_store':'MEMORY', 'PRAGMA cache_size':'5000000'})

db = sqlite_db_engine.connect()
Run Code Online (Sandbox Code Playgroud)

还有这个:

sqlite_db_engine = create_engine('sqlite:///%s' % str(dbname))

db = sqlite_db_engine.connect()
db.execute("PRAGMA journal_mode = MEMORY")
db.execute("PRAGMA synchronous = OFF")
db.execute("PRAGMA temp_store = MEMORY")
db.execute("PRAGMA cache_size = 500000")
Run Code Online (Sandbox Code Playgroud)

没有运气.对于长事务,我仍然可以看到在磁盘上创建的.journal文件.还有另一种设置方法吗?

*注意使用内置的python sqlite模块我没有问题

kal*_*alu 7

如何使用事件:

from sqlalchemy.engine import Engine
from sqlalchemy import event

@event.listens_for(Engine, "connect")
def set_sqlite_pragma(dbapi_connection, connection_record):
    cursor = dbapi_connection.cursor()
    cursor.execute("PRAGMA journal_mode=WAL")
    cursor.close()
Run Code Online (Sandbox Code Playgroud)

http://docs.sqlalchemy.org/en/rel_0_9/dialects/sqlite.html#foreign-key-support


Elr*_*ond 5

基本上你应该能够重写关于foreignkey的例子来实现你想要的.请查看/sf/answers/548184731/

engine = create_engine(database_url)

def _fk_pragma_on_connect(dbapi_con, con_record):
    dbapi_con.execute('PRAGMA journal_mode = MEMORY')
    # ...

from sqlalchemy import event
event.listen(engine, 'connect', _fk_pragma_on_connect)
Run Code Online (Sandbox Code Playgroud)