#navi(../)
* PythonでSQLite3に接続する [#y2b4a3a7]
PythonでSQLite3に接続し簡単な操作をする方法を以下に記します。~
尚、sqlite3のモジュールはPython2.5から標準ライブラリ入っています。

#contents
#htmlinsertpcsp(db-top.html,db-sp.html)

* 動作確認環境 [#of0ffcac]
 $ python --version
 Python 2.7.3

 $ lsb_release -d
 Description:    Ubuntu 12.04.4 LTS

* 関連記事 [#gcb5d4fe]


* SQLite3による前準備 [#bf729973]
sqlite3を起動し、以下のようにテーブルおよび1行挿入しました。~
本資料では、以下のテーブルを使用し説明します。
 $ sqlite3 foodb.sqlite3
 SQLite version 3.7.9 2011-11-01 00:52:41
 Enter ".help" for instructions
 Enter SQL statements terminated with a ";"
 sqlite> create table t1(c1,c2,c3);
 sqlite> insert into t1 values(1,2,3);
 sqlite> select count(*) from t1;
 1
 sqlite> .q

* PythonでSQLite3にアクセスする [#d1e58819]
上記で作成したsqlite3のデータベースに接続し(開き)、作成したテーブル内容を表示するサンプルコードです。
#ref(connect.py)
 #!/usr/bin/env python
 # -*- coding: utf-8 -*-
 import sqlite3
 
 dbfile = "foodb.sqlite3"
 con = sqlite3.connect(dbfile)
 # con = sqlite3.connect(dbfile, isolation_level=None) # auto commit mode
 cur = con.cursor()
 sql = u"select * from t1"
 cur.execute(sql)
 for r in cur:
   print r[0], r[1], r[2]
 
 con.close()

実行結果
 $ chmod +x connect.py
 $ ./connect.py
 1 2 3

上記でINSERTした内容が表示されます。

以上、PythonからSQLite3に接続しSELECTするサンプルコードでした。

#htmlinsertpcsp(db-btm.html,db-sp.html)

トップ   編集 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS