"sqlite3" — SQLite データベースに対する DB-API 2.0 インタフェース
*****************************************************************

バージョン 2.5 で追加.

SQLite は、軽量なディスク上のデータベースを提供する C ライブラリです。
別のサーバプロセスを用意する必要なく、 SQL クエリー言語の非標準的な一
種を使用してデータベースにアクセスできます。一部のアプリケーションは内
部データ保存に SQLite を使えます。また、SQLite を使ってアプリケーショ
ンのプロトタイプを作り、その後そのコードを PostgreSQL や Oracle のよう
な大規模データベースに移植するということも可能です。

sqlite3 モジュールの著者は Gerhard Häring です。 **PEP 249** で記述さ
れている DB-API 2.0 に準拠した SQL インターフェイスを提供します。

このモジュールを使うには、最初にデータベースを表す "Connection" オブジ
ェクトを作ります。ここではデータはファイル "example.db" に格納されてい
るものとします:

   import sqlite3
   conn = sqlite3.connect('example.db')

特別な名前である ":memory:" を使うと RAM 上にデータベースを作ることも
できます。

"Connection" があれば、 "Cursor" オブジェクトを作りその "execute()" メ
ソッドを呼んで SQL コマンドを実行することができます:

   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 connection if we are done with it.
   # Just be sure any changes have been committed or they will be lost.
   conn.close()

保存されたデータは永続的であり、次回のセッションでもそのまま使用できま
す:

   import sqlite3
   conn = sqlite3.connect('example.db')
   c = conn.cursor()

たいてい、SQL 操作では Python 変数の値を使う必要があります。この時、ク
エリーを Python の文字列操作を使って構築することは安全とは言えないので
、すべきではありません。そのようなことをするとプログラムが SQL インジ
ェクション攻撃に対し脆弱になります (https://xkcd.com/327/ ではどうなっ
てしまうかをユーモラスに描いています)。

代わりに、DB-API のパラメータ割り当てを使います。 "?" を変数の値を使い
たいところに埋めておきます。その上で、値のタプルをカーソルの
"execute()" メソッドの第2引数として引き渡します。(他のデータベースモジ
ュールでは変数の場所を示すのに "%s" や ":1" などの異なった表記を用いる
ことがあります。) 例を示します:

   # Never do this -- insecure!
   symbol = 'RHAT'
   c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)

   # Do this instead
   t = ('RHAT',)
   c.execute('SELECT * FROM stocks WHERE symbol=?', t)
   print c.fetchone()

   # Larger example that inserts many records at a time
   purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
                ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
                ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
               ]
   c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)

SELECT 文を実行した後データを取得する方法は3つありどれを使っても構いま
せん。一つはカーソルをイテレータ (*iterator*) として扱う、一つはカーソ
ルの "fetchone()" メソッドを呼んで一致した内の一行を取得する、もう一つ
は "fetchall()" メソッドを呼んで一致した全ての行のリストとして受け取る
、という3つです。

以下の例ではイテレータの形を使います:

   >>> for row in c.execute('SELECT * FROM stocks ORDER BY price'):
           print row

   (u'2006-01-05', u'BUY', u'RHAT', 100, 35.14)
   (u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)
   (u'2006-04-06', u'SELL', u'IBM', 500, 53.0)
   (u'2006-04-05', u'BUY', u'MSFT', 1000, 72.0)

参考:

  https://github.com/ghaering/pysqlite
     pysqlite のウェブページ – sqlite3 は「pysqlite」という名の下、外
     部で開発されています。

  https://www.sqlite.org
     SQLite のウェブページ。ここの文書ではサポートされる SQL 方言の文
     法と使えるデータ型を説明しています。

  http://www.w3schools.com/sql/
     SQL 学習に効くチュートリアル、リファレンス、実例集。

  **PEP 249** - Database API Specification 2.0
     Marc-Andre Lemburg により書かれた PEP。


モジュールの関数と定数
======================

sqlite3.version

   文字列で表現されたモジュールのバージョン番号です。これは SQLite ラ
   イブラリのバージョンではありません。

sqlite3.version_info

   整数のタプルで表現されたモジュールのバージョン番号です。これは
   SQLite ライブラリのバージョンではありません。

sqlite3.sqlite_version

   文字列で表現された SQLite ランタイムライブラリのバージョン番号です
   。

sqlite3.sqlite_version_info

   整数のタプルで表現された SQLite ランタイムライブラリのバージョン番
   号です。

sqlite3.PARSE_DECLTYPES

   この定数は "connect()" 関数の *detect_types* パラメータとして使われ
   ます。

   この定数を設定すると "sqlite3" モジュールは戻り値のカラムの宣言され
   た型を読み取るようになります。意味を持つのは宣言の最初の単語です。
   すなわち、」integer primary key」 においては 「integer」 が読み取ら
   れます。また、 「number(10)」 では、 「number」 が読み取られます。
   そして、そのカラムに対して、変換関数の辞書を探してその型に対して登
   録された関数を使うようにします。

sqlite3.PARSE_COLNAMES

   この定数は "connect()" 関数の *detect_types* パラメータとして使われ
   ます。

   この定数を設定すると SQLite のインタフェースは戻り値のそれぞれのカ
   ラムの名前を読み取るようになります。文字列の中の [mytype] といった
   形の部分を探し、』mytype』 がそのカラムの名前であると判断します。そ
   して 『mytype』 のエントリを変換関数辞書の中から見つけ、見つかった
   変換関数を値を返す際に用います。 "Cursor.description" で見つかるカ
   ラム名はその最初の単語だけです。すなわち、もし "'as "x
   [datetime]"'" のようなものを SQL の中で使っていたとすると、読み取る
   のはカラム名の中の最初の空白までの全てですので、カラム名として使わ
   れるのは単純に 「x」 ということになります。

sqlite3.connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements])

   ファイル *database* の SQLite データベースへの接続を開きます。
   "":memory:"" という名前を使うことでディスクの代わりに RAM 上のデー
   タベースへの接続を開くこともできます。

   データベースが複数の接続からアクセスされている状況で、その内の一つ
   がデータベースに変更を加えたとき、SQLite データベースはそのトランザ
   クションがコミットされるまでロックされます。*timeout* パラメータで
   、例外を送出するまで接続がロックが解除されるのをどれだけ待つかを決
   めます。デフォルトは 5.0 (5秒) です。

   For the *isolation_level* parameter, please see the
   "Connection.isolation_level" property of "Connection" objects.

   SQLite はネイティブで TEXT、INTEGER、REAL、BLOB および NULL のみを
   サポートしています。その他のタイプを使用したい場合はあなた自身で追
   加しなければなりません。*detect_types* パラメーターおよび、
   "register_converter()" 関数でモジュールレベルで登録できるカスタム
   **変換関数** を使用することで簡単に追加できます。

   パラメータ *detect_types* のデフォルトは 0 (つまりオフ、型検知無し)
   です。型検知を有効にするためには、 "PARSE_DECLTYPES" と
   "PARSE_COLNAMES" の適当な組み合わせをこのパラメータにセットします。

   デフォルトでは、 "sqlite3" モジュールは connect の呼び出しの際にモ
   ジュールの "Connection" クラスを使います。しかし、 "Connection" ク
   ラスを継承したクラスを *factory* パラメータに渡して "connect()" に
   そのクラスを使わせることもできます。

   詳しくはこのマニュアルの SQLite と Python の型 節を参考にしてくださ
   い。

   "sqlite3" モジュールは SQL 解析のオーバーヘッドを避けるために内部で
   文キャッシュを使っています。接続に対してキャッシュされる文の数を自
   分で指定したいならば、 *cached_statements* パラメータに設定してくだ
   さい。現在の実装ではデフォルトでキャッシュされる SQL 文の数を 100
   にしています。

sqlite3.register_converter(typename, callable)

   データベースから得られるバイト列を希望する Python の型に変換する呼
   び出し可能オブジェクト (callable) を登録します。その呼び出し可能オ
   ブジェクトは型が *typename* である全てのデータベース上の値に対して
   呼び出されます。型検知がどのように働くかについては "connect()" 関数
   の *detect_types* パラメータの説明も参照してください。注意が必要な
   のは *typename* はクエリの中の型名と大文字小文字も一致しなければな
   らないということです！

sqlite3.register_adapter(type, callable)

   Registers a callable to convert the custom Python type *type* into
   one of SQLite’s supported types. The callable *callable* accepts as
   single parameter the Python value, and must return a value of the
   following types: int, long, float, str (UTF-8 encoded), unicode or
   buffer.

sqlite3.complete_statement(sql)

   文字列 *sql* がセミコロンで終端された一つ以上の完全な SQL 文を含ん
   でいる場合、 "True" を返します。判定は SQL 文として文法的に正しいか
   ではなく、閉じられていない文字列リテラルが無いことおよびセミコロン
   で終端されていることだけで行われます。

   この関数は以下の例にあるような SQLite のシェルを作る際に使われます:

      # A minimal SQLite shell for experiments

      import sqlite3

      con = sqlite3.connect(":memory:")
      con.isolation_level = None
      cur = con.cursor()

      buffer = ""

      print "Enter your SQL commands to execute in sqlite3."
      print "Enter a blank line to exit."

      while True:
          line = raw_input()
          if line == "":
              break
          buffer += line
          if sqlite3.complete_statement(buffer):
              try:
                  buffer = buffer.strip()
                  cur.execute(buffer)

                  if buffer.lstrip().upper().startswith("SELECT"):
                      print cur.fetchall()
              except sqlite3.Error as e:
                  print "An error occurred:", e.args[0]
              buffer = ""

      con.close()

sqlite3.enable_callback_tracebacks(flag)

   デフォルトでは、ユーザ定義の関数、集計関数、変換関数、認可コールバ
   ックなどはトレースバックを出力しません。デバッグの際にはこの関数を
   *flag* に "True" を指定して呼び出します。そうした後は先に述べたよう
   な関数のトレースバックが "sys.stderr" に出力されます。元に戻すには
   "False" を使います。


Connection オブジェクト
=======================

class sqlite3.Connection

   SQLite データベースコネクション。以下の属性やメソッドを持ちます:

   isolation_level

      現在の分離レベルを取得または設定します。 "None" で自動コミットモ
      ードまたは 「DEFERRED」, 「IMMEDIATE」, 「EXLUSIVE」 のどれかで
      す。より詳しい説明は トランザクション制御 節を参照してください。

   cursor(factory=Cursor)

      cursor メソッドはオション引数 *factory* を 1 つだけ受け付けます
      。 渡された場合は、 "Cursor" またはそのサブクラスのインスタンス
      を返す呼び出し可能オブジェクトでなければなりません。

   commit()

      このメソッドは現在のトランザクションをコミットします。このメソッ
      ドを呼ばないと、前回 "commit()" を呼び出してから行ったすべての変
      更は、他のデータベースコネクションから見ることができません。もし
      、データベースに書き込んだはずのデータが見えなくて悩んでいる場合
      は、このメソッドの呼び出しを忘れていないかチェックしてください。

   rollback()

      このメソッドは最後に行った "commit()" 後の全ての変更をロールバッ
      クします。

   close()

      このメソッドはデータベースコネクションを閉じます。このメソッドが
      自動的に "commit()" を呼び出さないことに注意してください。
      "commit()" をせずにコネクションを閉じると、変更が消えてしまいま
      す！

   execute(sql[, parameters])

      This is a nonstandard shortcut that creates an intermediate
      cursor object by calling the cursor method, then calls the
      cursor’s "execute" method with the parameters given.

   executemany(sql[, parameters])

      This is a nonstandard shortcut that creates an intermediate
      cursor object by calling the cursor method, then calls the
      cursor’s "executemany" method with the parameters given.

   executescript(sql_script)

      This is a nonstandard shortcut that creates an intermediate
      cursor object by calling the cursor method, then calls the
      cursor’s "executescript" method with the parameters given.

   create_function(name, num_params, func)

      Creates a user-defined function that you can later use from
      within SQL statements under the function name *name*.
      *num_params* is the number of parameters the function accepts,
      and *func* is a Python callable that is called as the SQL
      function.

      The function can return any of the types supported by SQLite:
      unicode, str, int, long, float, buffer and "None".

      例:

         import sqlite3
         import md5

         def md5sum(t):
             return md5.md5(t).hexdigest()

         con = sqlite3.connect(":memory:")
         con.create_function("md5", 1, md5sum)
         cur = con.cursor()
         cur.execute("select md5(?)", ("foo",))
         print cur.fetchone()[0]

   create_aggregate(name, num_params, aggregate_class)

      ユーザ定義の集計関数を作成します。

      The aggregate class must implement a "step" method, which
      accepts the number of parameters *num_params*, and a "finalize"
      method which will return the final result of the aggregate.

      The "finalize" method can return any of the types supported by
      SQLite: unicode, str, int, long, float, buffer and "None".

      例:

         import sqlite3

         class MySum:
             def __init__(self):
                 self.count = 0

             def step(self, value):
                 self.count += value

             def finalize(self):
                 return self.count

         con = sqlite3.connect(":memory:")
         con.create_aggregate("mysum", 1, MySum)
         cur = con.cursor()
         cur.execute("create table test(i)")
         cur.execute("insert into test(i) values (1)")
         cur.execute("insert into test(i) values (2)")
         cur.execute("select mysum(i) from test")
         print cur.fetchone()[0]

   create_collation(name, callable)

      *name* と *callable* で指定される照合順序を作成します。呼び出し
      可能オブジェクトには二つの文字列が渡されます。一つめのものが二つ
      めのものより低く順序付けられるならば -1 を返し、等しければ 0 を
      返し、一つめのものが二つめのものより高く順序付けられるならば 1
      を返すようにしなければなりません。この関数はソート(SQL での
      ORDER BY)をコントロールするもので、比較を行なうことは他の SQL 操
      作には影響を与えないことに注意しましょう。

      また、呼び出し可能オブジェクトに渡される引数は Python のバイト文
      字列として渡されますが、それは通常 UTF-8 で符号化されたものにな
      ります。

      以下の例は「間違った方法で」ソートする自作の照合順序です:

         import sqlite3

         def collate_reverse(string1, string2):
             return -cmp(string1, string2)

         con = sqlite3.connect(":memory:")
         con.create_collation("reverse", collate_reverse)

         cur = con.cursor()
         cur.execute("create table test(x)")
         cur.executemany("insert into test(x) values (?)", [("a",), ("b",)])
         cur.execute("select x from test order by x collate reverse")
         for row in cur:
             print row
         con.close()

      照合順序を取り除くには callable に "None" を指定して
      "create_collation" を呼び出します:

         con.create_collation("reverse", None)

   interrupt()

      このメソッドを別スレッドから呼び出して接続上で現在実行中であろう
      クエリを中断させられます。クエリが中断されると呼び出し元は例外を
      受け取ります。

   set_authorizer(authorizer_callback)

      このルーチンはコールバックを登録します。コールバックはデータベー
      スのテーブルのカラムにアクセスしようとするたびに呼び出されます。
      コールバックはアクセスが許可されるならば "SQLITE_OK" を、SQL 文
      全体がエラーとともに中断されるべきならば "SQLITE_DENY" を、カラ
      ムが NULL 値として扱われるべきなら "SQLITE_IGNORE" を返さなけれ
      ばなりません。これらの定数は "sqlite3" モジュールに用意されてい
      ます。

      コールバックの第一引数はどの種類の操作が許可されるかを決めます。
      第二第三引数には第一引数に依存して本当に使われる引数か "None" か
      が渡されます。第四引数はもし適用されるならばデータベースの名前(
      「main」, 「temp」, etc.)です。第五引数はアクセスを試みる要因と
      なった最も内側のトリガまたはビューの名前、またはアクセスの試みが
      入力された SQL コードに直接起因するものならば "None" です。

      第一引数に与えることができる値や、その第一引数によって決まる第二
      第三引数の意味については、SQLite の文書を参考にしてください。必
      要な定数は全て "sqlite3" モジュールに用意されています。

   set_progress_handler(handler, n)

      このメソッドはコールバックを登録します。コールバックは SQLite 仮
      想マシン上の *n* 個の命令を実行するごとに呼び出されます。これは
      、GUI 更新などのために、長時間かかる処理中に SQLite からの呼び出
      しが欲しい場合に便利です。

      以前登録した progress handler をクリアしたい場合は、このメソッド
      を、 *handler* 引数に "None" を渡して呼び出してください。

      バージョン 2.6 で追加.

   enable_load_extension(enabled)

      このメソッドは SQLite エンジンが共有ライブラリから SQLite 拡張を
      読み込むのを許可したり、禁止したりします。SQLite 拡張は新しい関
      数や集計関数や仮想テーブルの実装を定義できます。1つの有名な拡張
      は SQLite によって頒布されている全テキスト検索拡張です。

      SQLite 拡張はデフォルトで無効にされています。[1] を見てください
      。

      バージョン 2.7 で追加.

         import sqlite3

         con = sqlite3.connect(":memory:")

         # enable extension loading
         con.enable_load_extension(True)

         # Load the fulltext search extension
         con.execute("select load_extension('./fts3.so')")

         # alternatively you can load the extension using an API call:
         # con.load_extension("./fts3.so")

         # disable extension loading again
         con.enable_load_extension(False)

         # example from SQLite wiki
         con.execute("create virtual table recipe using fts3(name, ingredients)")
         con.executescript("""
             insert into recipe (name, ingredients) values ('broccoli stew', 'broccoli peppers cheese tomatoes');
             insert into recipe (name, ingredients) values ('pumpkin stew', 'pumpkin onions garlic celery');
             insert into recipe (name, ingredients) values ('broccoli pie', 'broccoli cheese onions flour');
             insert into recipe (name, ingredients) values ('pumpkin pie', 'pumpkin sugar flour butter');
             """)
         for row in con.execute("select rowid, name, ingredients from recipe where name match 'pie'"):
             print row

   load_extension(path)

      このメソッドは共有ライブラリから SQLite 拡張を読み込みます。この
      メソッドを使う前に "enable_load_extension()" で拡張の読み込みを
      許可しておかなくてはなりません。

      SQLite 拡張はデフォルトで無効にされています。[1] を見てください
      。

      バージョン 2.7 で追加.

   row_factory

      この属性を変更して、カーソルと元の行をタプル形式で受け取り、本当
      の結果の行を返す呼び出し可能オブジェクトにすることができます。こ
      れによって、より進んだ結果の返し方を実装することができます。例え
      ば、各列に列名でもアクセスできるようなオブジェクトを返すことがで
      きます。

      例:

         import sqlite3

         def dict_factory(cursor, row):
             d = {}
             for idx, col in enumerate(cursor.description):
                 d[col[0]] = row[idx]
             return d

         con = sqlite3.connect(":memory:")
         con.row_factory = dict_factory
         cur = con.cursor()
         cur.execute("select 1 as a")
         print cur.fetchone()["a"]

      タプルを返すのでは物足りず、名前に基づいて列へアクセスしたい場合
      は、 "row_factory" に高度に最適化された "sqlite3.Row" 型を設定す
      ることを検討してください。 "Row" クラスではインデックスでも大文
      字小文字を無視した名前でも列にアクセスでき、しかもほとんどメモリ
      ーを浪費しません。おそらく独自実装の辞書を使うアプローチよりも良
      いもので、もしかすると db の行に基づいた解法よりも優れているかも
      しれません。

   text_factory

      Using this attribute you can control what objects are returned
      for the "TEXT" data type. By default, this attribute is set to
      "unicode" and the "sqlite3" module will return Unicode objects
      for "TEXT". If you want to return bytestrings instead, you can
      set it to "str".

      For efficiency reasons, there’s also a way to return Unicode
      objects only for non-ASCII data, and bytestrings otherwise. To
      activate it, set this attribute to "sqlite3.OptimizedUnicode".

      バイト列を受け取って望みの型のオブジェクトを返すような呼び出し可
      能オブジェクトを何でも設定して構いません。

      以下の説明用のコード例を参照してください:

         import sqlite3

         con = sqlite3.connect(":memory:")
         cur = con.cursor()

         AUSTRIA = u"\xd6sterreich"

         # by default, rows are returned as Unicode
         cur.execute("select ?", (AUSTRIA,))
         row = cur.fetchone()
         assert row[0] == AUSTRIA

         # but we can make sqlite3 always return bytestrings ...
         con.text_factory = str
         cur.execute("select ?", (AUSTRIA,))
         row = cur.fetchone()
         assert type(row[0]) is str
         # the bytestrings will be encoded in UTF-8, unless you stored garbage in the
         # database ...
         assert row[0] == AUSTRIA.encode("utf-8")

         # we can also implement a custom text_factory ...
         # here we implement one that will ignore Unicode characters that cannot be
         # decoded from UTF-8
         con.text_factory = lambda x: unicode(x, "utf-8", "ignore")
         cur.execute("select ?", ("this is latin1 and would normally create errors" +
                                  u"\xe4\xf6\xfc".encode("latin1"),))
         row = cur.fetchone()
         assert type(row[0]) is unicode

         # sqlite3 offers a built-in optimized text_factory that will return bytestring
         # objects, if the data is in ASCII only, and otherwise return unicode objects
         con.text_factory = sqlite3.OptimizedUnicode
         cur.execute("select ?", (AUSTRIA,))
         row = cur.fetchone()
         assert type(row[0]) is unicode

         cur.execute("select ?", ("Germany",))
         row = cur.fetchone()
         assert type(row[0]) is str

   total_changes

      データベース接続が開始されて以来の行の変更・挿入・削除がなされた
      行の総数を返します。

   iterdump

      データベースをSQL testフォーマットでダンプするためのイテレータを
      返します。 メモリ内のデータベースの内容を、後で復元するために保
      存する場合に便利です。この関数には、 **sqlite3** シェルの中の
      ".dump" コマンドと同じ機能があります。

      バージョン 2.6 で追加.

      以下はプログラム例です:

         # Convert file existing_db.db to SQL dump file dump.sql
         import sqlite3, os

         con = sqlite3.connect('existing_db.db')
         with open('dump.sql', 'w') as f:
             for line in con.iterdump():
                 f.write('%s\n' % line)


カーソルオブジェクト
====================

class sqlite3.Cursor

   "Cursor" インスタンスは以下の属性やメソッドを持ちます。

   execute(sql[, parameters])

      SQL 文を実行します。SQL 文はパラメータ化できます(すなわち SQL リ
      テラルの代わりの場所確保文字 (placeholder) を入れておけます)。
      "sqlite3" モジュールは2種類の場所確保記法をサポートします。一つ
      は疑問符(qmark スタイル)、もう一つは名前(named スタイル)です。

      両方のスタイルの例です:

         import sqlite3

         con = sqlite3.connect(":memory:")
         cur = con.cursor()
         cur.execute("create table people (name_last, age)")

         who = "Yeltsin"
         age = 72

         # This is the qmark style:
         cur.execute("insert into people values (?, ?)", (who, age))

         # And this is the named style:
         cur.execute("select * from people where name_last=:who and age=:age", {"who": who, "age": age})

         print cur.fetchone()

      "execute()" will only execute a single SQL statement. If you try
      to execute more than one statement with it, it will raise a
      Warning. Use "executescript()" if you want to execute multiple
      SQL statements with one call.

   executemany(sql, seq_of_parameters)

      Executes an SQL command against all parameter sequences or
      mappings found in the sequence *sql*.  The "sqlite3" module also
      allows using an *iterator* yielding parameters instead of a
      sequence.

         import sqlite3

         class IterChars:
             def __init__(self):
                 self.count = ord('a')

             def __iter__(self):
                 return self

             def next(self):
                 if self.count > ord('z'):
                     raise StopIteration
                 self.count += 1
                 return (chr(self.count - 1),) # this is a 1-tuple

         con = sqlite3.connect(":memory:")
         cur = con.cursor()
         cur.execute("create table characters(c)")

         theIter = IterChars()
         cur.executemany("insert into characters(c) values (?)", theIter)

         cur.execute("select c from characters")
         print cur.fetchall()

      もう少し短いジェネレータ (*generator*) を使った例です:

         import sqlite3
         import string

         def char_generator():
             for c in string.lowercase:
                 yield (c,)

         con = sqlite3.connect(":memory:")
         cur = con.cursor()
         cur.execute("create table characters(c)")

         cur.executemany("insert into characters(c) values (?)", char_generator())

         cur.execute("select c from characters")
         print cur.fetchall()

   executescript(sql_script)

      これは非標準の便宜メソッドで、一度に複数の SQL 文を実行すること
      ができます。メソッドは最初に "COMMIT" 文を発行し、次いで引数とし
      て渡された SQLスクリプトを実行します。

      *sql_script* can be a bytestring or a Unicode string.

      例:

         import sqlite3

         con = sqlite3.connect(":memory:")
         cur = con.cursor()
         cur.executescript("""
             create table person(
                 firstname,
                 lastname,
                 age
             );

             create table book(
                 title,
                 author,
                 published
             );

             insert into book(title, author, published)
             values (
                 'Dirk Gently''s Holistic Detective Agency',
                 'Douglas Adams',
                 1987
             );
             """)

   fetchone()

      クエリ結果から次の row をフェッチして、1つのシーケンスを返します
      。これ以上データがない場合は "None" を返します。

   fetchmany([size=cursor.arraysize])

      クエリ結果から次の幾つかの row をフェッチして、リストを返します
      。これ以上データがない場合は空のリストを返します。

      一回の呼び出しで返される row の数は、*size* 引数で指定できます。
      この引数が与えられない場合、cursor の arraysize 属性が利用されま
      す。このメソッドは可能な限り指定された *size* の数の row を
      fetch しようとするべきです。もし、指定された数の row が利用可能
      でない場合、それより少ない数の row が返されます。

      *size* 引数とパフォーマンスの関係についての注意です。パフォーマ
      ンスを最適化するためには、大抵、 arraysize 属性を利用するのがベ
      ストです。 *size* 引数を利用したのであれば、次の "fetchmany()"
      の呼び出しでも同じ数を利用するのがベストです。

   fetchall()

      全ての(残りの)クエリ結果の row をフェッチして、リストを返します
      。cursor の arraysize 属性がこの操作のパフォーマンスに影響するこ
      とに気をつけてください。これ以上の row がない場合は、空のリスト
      が返されます。

   rowcount

      一応 "sqlite3" モジュールの "Cursor" クラスはこの属性を実装して
      いますが、データベースエンジン自身の「影響を受けた行」/「選択さ
      れた行」の決定方法は少し風変わりです。

      "executemany()" では、変更数が "rowcount" に合計されます。

      Python DB API 仕様で要求されるように、"rowcount" 属性は「カーソ
      ルに対して "executeXX()" が行なわれていないか、最後の操作の
      rowcount がインターフェースによって決定できなかった場合は -1 」
      です。これには "SELECT" 文も含まれます。すべての列を取得するまで
      クエリによって生じた列の数を決定できないからです。

      SQLite のバージョン 3.6.5 以前は、条件なしで "DELETE FROM table"
      を実行すると "rowcount" が 0 にセットされます。

   lastrowid

      This read-only attribute provides the rowid of the last modified
      row. It is only set if you issued an "INSERT" statement using
      the "execute()" method. For operations other than "INSERT" or
      when "executemany()" is called, "lastrowid" is set to "None".

   description

      この読み込み専用の属性は、最後のクエリの結果のカラム名を提供しま
      す。 Python DB API との互換性を維持するために、各カラムに対して
      7つのタプルを返しますが、タプルの後ろ6つの要素は全て "None" です
      。

      この属性は "SELECT" 文にマッチする row が1つもなかった場合でもセ
      ットされます。

   connection

      この読み込み専用の属性は、 "Cursor" オブジェクトが使用する
      SQLite データベースの "Connection" を提供します。"con.cursor()"
      を呼び出すことにより作成される "Cursor" オブジェクトは、 *con*
      を参照する "connection" 属性を持ちます:

         >>> con = sqlite3.connect(":memory:")
         >>> cur = con.cursor()
         >>> cur.connection == con
         True


Row オブジェクト
================

class sqlite3.Row

   "Row" インスタンスは、 "Connection" オブジェクトの "row_factory" と
   して高度に最適化されています。タプルによく似た機能を持つ row を作成
   します。

   カラム名とインデックスによる要素へのアクセス, イテレーション,
   repr(), 同値テスト, "len()" をサポートしています。

   もし、2つの "Row" オブジェクトが完全に同じカラムと値を持っていた場
   合、それらは同値になります。

   バージョン 2.6 で変更: Added iteration and equality (hashability).

   keys()

      このメソッドはカラム名のリストを返します。クエリ直後から、これは
      "Cursor.description" の各タプルの最初のメンバになります。

      バージョン 2.6 で追加.

Rowの例のために、まずサンプルのテーブルを初期化します:

   conn = sqlite3.connect(":memory:")
   c = conn.cursor()
   c.execute('''create table stocks
   (date text, trans text, symbol text,
    qty real, price real)''')
   c.execute("""insert into stocks
             values ('2006-01-05','BUY','RHAT',100,35.14)""")
   conn.commit()
   c.close()

そして、 "Row" を使ってみます:

   >>> conn.row_factory = sqlite3.Row
   >>> c = conn.cursor()
   >>> c.execute('select * from stocks')
   <sqlite3.Cursor object at 0x7f4e7dd8fa80>
   >>> r = c.fetchone()
   >>> type(r)
   <type 'sqlite3.Row'>
   >>> r
   (u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.14)
   >>> len(r)
   5
   >>> r[2]
   u'RHAT'
   >>> r.keys()
   ['date', 'trans', 'symbol', 'qty', 'price']
   >>> r['qty']
   100.0
   >>> for member in r:
   ...     print member
   ...
   2006-01-05
   BUY
   RHAT
   100.0
   35.14


SQLite と Python の型
=====================


はじめに
--------

SQLite は以下の型をネイティブにサポートします: "NULL", "INTEGER",
"REAL", "TEXT", "BLOB"。

したがって、次の Python の型は問題なく SQLite に送り込めます:

+-------------------------------+---------------+
| Python の型                   | SQLite の型   |
+===============================+===============+
| "None"                        | "NULL"        |
+-------------------------------+---------------+
| "int"                         | "INTEGER"     |
+-------------------------------+---------------+
| "long"                        | "INTEGER"     |
+-------------------------------+---------------+
| "float"                       | "REAL"        |
+-------------------------------+---------------+
| "str" (UTF8-encoded)          | "TEXT"        |
+-------------------------------+---------------+
| "unicode"                     | "TEXT"        |
+-------------------------------+---------------+
| "buffer"                      | "BLOB"        |
+-------------------------------+---------------+

SQLite の型から Python の型へのデフォルトでの変換は以下の通りです:

+---------------+------------------------------------------------+
| SQLite の型   | Python の型                                    |
+===============+================================================+
| "NULL"        | "None"                                         |
+---------------+------------------------------------------------+
| "INTEGER"     | "int" or "long", depending on size             |
+---------------+------------------------------------------------+
| "REAL"        | "float"                                        |
+---------------+------------------------------------------------+
| "TEXT"        | depends on "text_factory", "unicode" by        |
|               | default                                        |
+---------------+------------------------------------------------+
| "BLOB"        | "buffer"                                       |
+---------------+------------------------------------------------+

"sqlite3" モジュールの型システムは二つの方法で拡張できます。一つはオブ
ジェクト適合(adaptation)を通じて追加された Python の型を SQLite に格納
することです。もう一つは変換関数(converter)を通じて "sqlite3" モジュー
ルに SQLite の型を違った Python の型に変換させることです。


追加された Python の型を SQLite データベースに格納するために適合関数を使う
--------------------------------------------------------------------------

As described before, SQLite supports only a limited set of types
natively. To use other Python types with SQLite, you must **adapt**
them to one of the sqlite3 module’s supported types for SQLite: one of
NoneType, int, long, float, str, unicode, buffer.

"sqlite3" モジュールで望みの Python の型をサポートされている型の一つに
適合させる方法は二つあります。


オブジェクト自身で適合するようにする
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

自分でクラスを書いているならばこの方法が良いでしょう。次のようなクラス
があるとします:

   class Point(object):
       def __init__(self, x, y):
           self.x, self.y = x, y

さてこの点を SQLite の一つのカラムに収めたいと考えたとしましょう。最初
にしなければならないのはサポートされている型の中から点を表現するのに使
えるものを選ぶことです。ここでは単純に文字列を使うことにして、座標を区
切るのにはセミコロンを使いましょう。次に必要なのはクラスに変換された値
を返す "__conform__(self, protocol)" メソッドを追加することです。引数
*protocol* は "PrepareProtocol" になります。

   import sqlite3

   class Point(object):
       def __init__(self, x, y):
           self.x, self.y = x, y

       def __conform__(self, protocol):
           if protocol is sqlite3.PrepareProtocol:
               return "%f;%f" % (self.x, self.y)

   con = sqlite3.connect(":memory:")
   cur = con.cursor()

   p = Point(4.0, -3.2)
   cur.execute("select ?", (p,))
   print cur.fetchone()[0]


適合関数を登録する
~~~~~~~~~~~~~~~~~~

もう一つの可能性は型を文字列表現に変換する関数を作り
"register_adapter()" でその関数を登録することです。

注釈: The type/class to adapt must be a *new-style class*, i. e. it
  must have "object" as one of its bases.

   import sqlite3

   class Point(object):
       def __init__(self, x, y):
           self.x, self.y = x, y

   def adapt_point(point):
       return "%f;%f" % (point.x, point.y)

   sqlite3.register_adapter(Point, adapt_point)

   con = sqlite3.connect(":memory:")
   cur = con.cursor()

   p = Point(4.0, -3.2)
   cur.execute("select ?", (p,))
   print cur.fetchone()[0]

"sqlite3" モジュールには二つの Python 標準型 "datetime.date" と
"datetime.datetime" に対するデフォルト適合関数があります。いま
"datetime.datetime" オブジェクトを ISO 表現でなく Unix タイムスタンプ
として格納したいとしましょう。

   import sqlite3
   import datetime, time

   def adapt_datetime(ts):
       return time.mktime(ts.timetuple())

   sqlite3.register_adapter(datetime.datetime, adapt_datetime)

   con = sqlite3.connect(":memory:")
   cur = con.cursor()

   now = datetime.datetime.now()
   cur.execute("select ?", (now,))
   print cur.fetchone()[0]


SQLite の値を好きな Python 型に変換する
---------------------------------------

適合関数を書くことで好きな Python 型を SQLite に送り込めるようになりま
した。しかし、本当に使い物になるようにするには Python から SQLite さら
に Python へという往還(roundtrip)の変換ができる必要があります。

そこで変換関数(converter)です。

"Point" クラスの例に戻りましょう。x, y 座標をセミコロンで区切った文字
列として SQLite に格納したのでした。

まず、文字列を引数として取り "Point" オブジェクトをそれから構築する変
換関数を定義します。

注釈: Converter functions **always** get called with a string, no
  matter under which data type you sent the value to SQLite.

   def convert_point(s):
       x, y = map(float, s.split(";"))
       return Point(x, y)

次に "sqlite3" モジュールにデータベースから取得したものが本当に点であ
ることを教えなければなりません。二つの方法があります:

* 宣言された型を通じて暗黙的に

* カラム名を通じて明示的に

どちらの方法も モジュールの関数と定数 節の中で説明されています。それぞ
れ "PARSE_DECLTYPES" 定数と "PARSE_COLNAMES" 定数の項目です。

以下の例で両方のアプローチを紹介します。

   import sqlite3

   class Point(object):
       def __init__(self, x, y):
           self.x, self.y = x, y

       def __repr__(self):
           return "(%f;%f)" % (self.x, self.y)

   def adapt_point(point):
       return "%f;%f" % (point.x, point.y)

   def convert_point(s):
       x, y = map(float, s.split(";"))
       return Point(x, y)

   # Register the adapter
   sqlite3.register_adapter(Point, adapt_point)

   # Register the converter
   sqlite3.register_converter("point", convert_point)

   p = Point(4.0, -3.2)

   #########################
   # 1) Using declared types
   con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)
   cur = con.cursor()
   cur.execute("create table test(p point)")

   cur.execute("insert into test(p) values (?)", (p,))
   cur.execute("select p from test")
   print "with declared types:", cur.fetchone()[0]
   cur.close()
   con.close()

   #######################
   # 1) Using column names
   con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES)
   cur = con.cursor()
   cur.execute("create table test(p)")

   cur.execute("insert into test(p) values (?)", (p,))
   cur.execute('select p as "p [point]" from test')
   print "with column names:", cur.fetchone()[0]
   cur.close()
   con.close()


デフォルトの適合関数と変換関数
------------------------------

datetime モジュールの date 型および datetime 型のためのデフォルト適合
関数があります。これらの型は ISO 日付 / ISO タイムスタンプとして
SQLite に送られます。

デフォルトの変換関数は "datetime.date" 用が 「date」 という名前で、
"datetime.datetime" 用が 「timestamp」 という名前で登録されています。

これにより、多くの場合特別な細工無しに Python の日付 / タイムスタンプ
を使えます。適合関数の書式は実験的な SQLite の date/time 関数とも互換
性があります。

以下の例でこのことを確かめます。

   import sqlite3
   import datetime

   con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
   cur = con.cursor()
   cur.execute("create table test(d date, ts timestamp)")

   today = datetime.date.today()
   now = datetime.datetime.now()

   cur.execute("insert into test(d, ts) values (?, ?)", (today, now))
   cur.execute("select d, ts from test")
   row = cur.fetchone()
   print today, "=>", row[0], type(row[0])
   print now, "=>", row[1], type(row[1])

   cur.execute('select current_date as "d [date]", current_timestamp as "ts [timestamp]"')
   row = cur.fetchone()
   print "current_date", row[0], type(row[0])
   print "current_timestamp", row[1], type(row[1])

SQLite に格納されているタイムスタンプが6桁より長い小数部を持っている場
合、タイムスタンプの変換関数によってマイクロ秒精度に丸められます。


トランザクション制御
====================

By default, the "sqlite3" module opens transactions implicitly before
a Data Modification Language (DML)  statement (i.e.
"INSERT"/"UPDATE"/"DELETE"/"REPLACE"), and commits transactions
implicitly before a non-DML, non-query statement (i. e. anything other
than "SELECT" or the aforementioned).

So if you are within a transaction and issue a command like "CREATE
TABLE ...", "VACUUM", "PRAGMA", the "sqlite3" module will commit
implicitly before executing that command. There are two reasons for
doing that. The first is that some of these commands don’t work within
transactions. The other reason is that sqlite3 needs to keep track of
the transaction state (if a transaction is active or not).

sqlite3 が暗黙のうちに実行する "BEGIN" 文の種類(またはそういうものを使
わないこと)を "connect()" 呼び出しの *isolation_level* パラメータを通
じて、または接続の "isolation_level" プロパティを通じて、制御すること
ができます。

**自動コミットモード** を使いたい場合は、 "isolation_level" は "None"
にしてください。

そうでなければデフォルトのまま "BEGIN" 文を使い続けるか、SQLite がサポ
ートする分離レベル 「DEFERRED」, 「IMMEDIATE」 または 「EXCLUSIVE」 を
設定してください。


"sqlite3" の効率的な使い方
==========================


ショートカットメソッドを使う
----------------------------

"Connection" オブジェクトの非標準的なメソッド "execute()",
"executemany()", "executescript()" を使うことで、 (しばしば余計な)
"Cursor" オブジェクトをわざわざ作り出さずに済むので、コードをより簡潔
に書くことができます。 "Cursor" オブジェクトは暗黙裡に生成されショート
カットメソッドの戻り値として受け取ることができます。この方法を使えば、
"SELECT" 文を実行してその結果について反復することが、 "Connection" オ
ブジェクトに対する呼び出し一つで行なえます。

   import sqlite3

   persons = [
       ("Hugo", "Boss"),
       ("Calvin", "Klein")
       ]

   con = sqlite3.connect(":memory:")

   # Create the table
   con.execute("create table person(firstname, lastname)")

   # Fill the table
   con.executemany("insert into person(firstname, lastname) values (?, ?)", persons)

   # Print the table contents
   for row in con.execute("select firstname, lastname from person"):
       print row

   print "I just deleted", con.execute("delete from person").rowcount, "rows"


位置ではなく名前でカラムにアクセスする
--------------------------------------

"sqlite3" モジュールの有用な機能の一つに、行生成関数として使われるため
の "sqlite3.Row" クラスがあります。

このクラスでラップされた行は、位置インデクス(タプルのような)でも大文字
小文字を区別しない名前でもアクセスできます:

   import sqlite3

   con = sqlite3.connect(":memory:")
   con.row_factory = sqlite3.Row

   cur = con.cursor()
   cur.execute("select 'John' as name, 42 as age")
   for row in cur:
       assert row[0] == row["name"]
       assert row["name"] == row["nAmE"]
       assert row[1] == row["age"]
       assert row[1] == row["AgE"]


コネクションをコンテキストマネージャーとして利用する
----------------------------------------------------

バージョン 2.6 で追加.

Connection オブジェクトはコンテキストマネージャーとして利用して、トラ
ンザクションを自動的にコミットしたりロールバックすることができます。例
外が発生したときにトランザクションはロールバックされ、それ以外の場合、
トランザクションはコミットされます:

   import sqlite3

   con = sqlite3.connect(":memory:")
   con.execute("create table person (id integer primary key, firstname varchar unique)")

   # Successful, con.commit() is called automatically afterwards
   with con:
       con.execute("insert into person(firstname) values (?)", ("Joe",))

   # con.rollback() is called after the with block finishes with an exception, the
   # exception is still raised and must be caught
   try:
       with con:
           con.execute("insert into person(firstname) values (?)", ("Joe",))
   except sqlite3.IntegrityError:
       print "couldn't add Joe twice"


既知の問題
==========


マルチスレッド
--------------

古いバージョンの SQLite はスレッド間でのコネクションの共有に問題があり
ました。その理由は、Python のモジュールではスレッド間のコネクションと
カーソルの共有ができないためです。依然としてそのようなことをしようとす
ると、実行時に例外を受け取るでしょう。

唯一の例外は "interrupt()" メソッドで、これだけが異なるスレッドから呼
び出せます。

-[ 脚注 ]-

[1] The sqlite3 module is not built with loadable extension
    support by default, because some platforms (notably Mac OS X) have
    SQLite libraries which are compiled without this feature. To get
    loadable extension support, you must modify setup.py and remove
    the line that sets SQLITE_OMIT_LOAD_EXTENSION.
