PythonのSQLiteインターフェースを使用するときに、Cursorオブジェクトを作成する必要があるのかという話
小ネタ。Pythonのsqliteインターフェースを使用するとき、cursor()オブジェクトを作成する必要があるかどうかの話。 Pythonのsqliteインターフェースを使用する際、公式のドキュメントなどではConnectionオブジェクトを作成し、それを用いて更にCursorオブジェクトを作ってからexecute()メソッドなどを読んでいます。 公式のドキュメントより引用
conn = sqlite3.connect('/tmp/example')
c = conn.cursor()
# Create table
c.execute('''create table stocks
(date text, trans text, symbol text,
qty real, price real)''')
# Insert a row of data
c.execute("""insert into stocks
values ('2006-01-05','BUY','RHAT',100,35.14)""")
# Save (commit) the changes
conn.commit()
# We can also close the cursor if we are done with it
c.close()
しかし、いくつかのPythonの解説サイトでは、Cursorオブジェクトを作成せずConnectionオブジェクトから直接execute()メソッドを呼び出しています。 SEの日記様より引用
#!/usr/bin/env python
import csv
import sqlite3
import time
if __name__ == '__main__':
start = time.time()
c = sqlite3.connect('./testdb')
i = 0
l =
reader = csv.reader(open("./neta.csv"))
for row in reader:
id = row[0]
value = row[1]
t = (id,value)
l.append(t)
i += 1
if i % 200000 == 0:
c.executemany('insert into hash (id,value), values(?,?)',l)
c.commit()
l =
c.commit()
c.close()
print time.time()-start
結論から言うと、どっちでもいいみたいです。公式のドキュメントによると、Connectionオブジェクトからexecute()メソッドなどを呼び出すのは nonstandard な書き方みたいですが、別に非推奨というわけでもありません。好きなほうを使いましょう。