YAMAGUCHI::weblog

海水パンツとゴーグルで、巨万の富を築きました。カリブの怪物、フリーアルバイター瞳です。

pysqlite3.xでSQLiteを動かす

動機

なんとなく動かしてみようと思った。

方法

なんかライブラリリファレンスのサンプルだと微妙に文が足りない。

たぶんこっちの方がいいと思う。

で、こんな感じでテスト。

import sqlite3
"""
test.dbにはtesttableがある。
testtableの定義は
create table testtable (id int, name text)
"""
c = sqlite3.connect('test.db')
cur = c.cursor()

# %を使って値を渡すのはSQLインジェクションの原因
for t in ((1, 'hoge'), (2, 'piyo'), (3, 'fuga')):
    cur.execute('insert into testtable values (?, ?)', t)
c.commit() # コミットしないと反映されない

cur.execute('select * from testtable')
for row in cur: # カーソルをイテレータとして使用
    print row

list = cur.fetchall() # 結果の全行をリストとして取得
print list