如何使用SQLAlchemy设置SQLite PRAGMA语句

时间:2012-03-12 17:04:52

标签: 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()

和此:

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")

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

*注意我使用内置的python sqlite模块

进行此操作没有问题

3 个答案:

答案 0 :(得分: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()

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

答案 1 :(得分:5)

基本上你应该能够重写关于foreignkey的例子来实现你想要的。看看https://stackoverflow.com/a/7831210/1890086

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)

答案 2 :(得分:1)

以前的两个解决方案都不起作用,所以我找到了the another one

from sqlalchemy.interfaces import PoolListener
class MyListener(PoolListener):
    def connect(self, dbapi_con, con_record):
        dbapi_con.execute('pragma journal_mode=OFF')
        dbapi_con.execute('PRAGMA synchronous=OFF')
        dbapi_con.execute('PRAGMA cache_size=100000')

engine = create_engine('sqlite:///' + basefile,echo=False, listeners= [MyListener()])