SQLObjectを使ってsqliteを扱うときは、大量のデータを挿入する場合はトランザクションしないと使い物にならない

ここを参照して実験してみた。

例えば以下のようなトランザクションしない場合と、

  • ケース1
from sqlobject import *
import sys, os

db_filename = os.path.abspath('data.db')
if os.path.exists(db_filename):
  os.unlink(db_filename)

connection_string = 'sqlite:' + db_filename
connection = connectionForURI(connection_string)
sqlhub.processConnection = connection

class Person(SQLObject):
  firstName = StringCol()
  middleInitial = StringCol(length=1, default=None)
  lastName = StringCol()

Person._connection.debug = True

existDb = os.path.exists(db_filename)
if not existDb:
  Person.createTable()

for i in xrange(100):
  print i
  Person(firstName="%s"%i, lastName="%s"%i)

SQLObjectの機能を使ってトランザクションを行う場合を書いたとき、

  • ケース2
from sqlobject import *
import sys, os

db_filename = os.path.abspath('data.db')
if os.path.exists(db_filename):
  os.unlink(db_filename)

connection_string = 'sqlite:' + db_filename
connection = connectionForURI(connection_string)
sqlhub.processConnection = connection


class Person(SQLObject):
  firstName = StringCol()
  middleInitial = StringCol(length=1, default=None)
  lastName = StringCol()

existDb = os.path.exists(db_filename)
if not existDb:
  Person.createTable()

Person._connection.debug = True

def func():
  for i in xrange(100):
    print i
    Person(firstName="%s"%i, lastName="%s"%i)

sqlhub.doInTransaction(func)

ケース1は8秒かかるが、ケース2は0.5秒で終わる。SQLObjectを用いてSQLiteを操作するときはトランザクションを行わないと速度的に使い物にならない。