2012-03-12 84 views
11

我希望SQLAlchemy將SQLite .journal文件放在內存中以加速性能。我曾經嘗試這樣做:如何使用SQLAlchemy設置SQLite PRAGMA語句

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的模塊

+0

我也嘗試添加一個監聽器這樣的主題:http://stackoverflow.com/questions/2614984/sqlite-sqlalchemy-how-to-enforce-foreign-keys – tomc 2012-03-12 18:35:12

+0

我得到的錯誤'DBAPIError: (TypeError)當我嘗試使用您的代碼時,'PRAGMA cache_size'是此函數的無效關鍵字參數None None'。你得到的同樣的錯誤? – Nilesh 2012-03-14 05:34:18

+0

我沒有得到任何錯誤,代碼執行得很好,但顯然什麼都不做。 – tomc 2012-03-27 15:24:18

回答

5

這樣做基本上你應該能夠改寫有關外鍵的例子來實現你想要的。看看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) 
0

兩個以前的解決方案沒有工作,所以我發現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()]) 
+1

在最近的版本中,這將給出:SADeprecationWarning:池(和create_engine())的'監聽者'參數已被棄用。使用event.listen() – jpoppe 2015-12-19 11:14:43