pythonのsqlite3モジュールでトランザクションする方法メモ
pythonのsqlite3モジュールでトランザクションする方法をメモしておきます。なんか、ネットで調べてもなかなか日本語のサンプルが出てこなかったので。
sqlite3.connect()のisolation_levelオプション引数に分離レベルに対応する値を渡すだけです。
こんな形になります。以下サンプル。
import sqlite3 conn = None #conn = type('foo', (object, ), {'rollback':lambda self:None, 'commit':lambda self:None})() try: conn = sqlite3.connect(dbpath, isolation_level='EXCLUSIVE') # do something for i in range(10): conn.execute('insert into tbl values (?, ?)', [i, 'name%d' % i]) # except Exception, e: print e if conn: conn.rollback() finally: if conn: conn.commit()
分離レベルは3つあります。*1
分離レベル | 設定値 | 挙動 |
---|---|---|
deferred | 'DEFERRED' | 読み込み処理時にSHAREDロックを、書き込み処理時にRESERVEDロックを取得する*2 |
immediate | 'IMMEDIATE' | 開始時にRESERVEDロックを取得する*3 |
exclusive | 'EXCLUSIVE' | 開始時にEXCLUSIVEロックを取得する*4 |
auto commit | None | トランザクションでない時のモード。DML発行前に暗黙的なトランザクションを開始し、DDL発行前にコミット(とどこかで読んだけど公式文書を見つけられない) |
ロックの種類は http://www.sqlite.org/lockingv3.html#locking を参照。
また、ロックの粒度はデータベース全体です。*5
pythonアプリケーションのコードを書くときはここら辺が参考になります。
http://www.doughellmann.com/PyMOTW/sqlite3/
sqlite3の3つの分離レベル、DEFERRED, IMMEDIATE, EXCLUSIVEのそれぞれについて詳細な説明があります。しかもpythonのsqlite3による説明つき。
*1:http://www.sqlite.org/lang_transaction.html
*2:"The first read operation against a database creates a SHARED lock and the first write operation creates a RESERVED lock."
*3:"RESERVED locks are acquired on all databases as soon as the BEGIN command is executed, without waiting for the database to be used"
*4:"no other database connection except for read_uncommitted connections will be able to read the database and no other connection without exception will be able to write the database until the transaction is complete. "
*5:http://www.sqlite.org/whentouse.html "SQLite uses reader/writer locks on the entire database file."