sqlite3ライブラリはpython の標準ライブラリです。
SQLite と python の接続
Connection オブジェクト
python から SQLite に接続するためにはまずモジュールをインポートして、connect 関数を使ってConnection オブジェクトというオブジェクトを作ります。
SQLite はデータベースに登録されたデータをファイルに書き出すため、connect 関数の第1引数にファイルのパスを指定します。
import sqlite3
#ここではデータはファイル example.db に格納されているものとします。
conn = sqlite3.connect('example.db')
特別な名前である :memory: を使うと RAM 上にデータベースを作ることもできます。
import sqlite3
conn = sqlite3.connect(':memory:')
Cursor オブジェクト
Connection オブジェクトを作ったら次は Cursor オブジェクトを作ります。
データベースとのやりとりはこの Cursor オブジェクトを経由して行います。
Cursor オブジェクトを作りその execute() メソッドを呼んで SQL コマンドを実行することができます。
import sqlite3
#Connection オブジェクト作成(データベースの作成)
conn = sqlite3.connect(':memory:')
#Cursor オブジェクト作成
c = conn.cursor()
#sql文。テーブル作成
sql_table = '''
create table stocks
(date text, trans text, symbol text, qty real, price real)
'''
c.execute(sql_table)
#sql文。テーブルのカラムに値を登録
sql_insert = '''
INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)
'''
c.execute(sql_insert )
#セーブする。
conn.commit()
#データベースを閉じる
conn.close()
データの取り出し
データベースに保存したデータを取り出し、その取り出したデータをブラウザに表示させます。
import sqlite3
conn = sqlite3.connect(':memory:')
c = conn.cursor()
#sql文。テーブル作成
sql_table = '''
create table stocks
(date text, trans text, symbol text, qty real, price real)
'''
c.execute(sql_table)
#sql文。テーブルのカラムに値を登録
sql_insert = '''
INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)
'''
c.execute(sql_insert )
#sql文。テーブルのdate カラム値の値を取り出し変数aに格納
a = c.execute("SELECT date FROM stocks")
print('Content-type: text/html; charset=UTF-8\n')
for aa in a:
print(aa)
26行目で出力しています。
executeメソッドの返す値はiter型のようなのでfor文で出力しています。