Connection のインスタンスには以下の属性とメソッドがあります:
| [cursorClass]) |
| sql, [parameters]) |
| sql, [parameters]) |
| sql_script) |
| name, num_params, func) |
関数は SQLite でサポートされている任意の型を返すことができます。具体的には unicode, str, int, long, float, buffer および 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]
| name, num_params, aggregate_class) |
ユーザ定義の集計関数を作成します。
集計クラスには パラメータ num_params で指定される個数の引数を取る
step メソッドおよび最終的な集計結果を返す finalize メソッドを
実装しなければなりません。
finalize メソッドは SQLite でサポートされている任意の型を返すことができます。
具体的には unicode, str, int, long, float, buffer および 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]
| name, callable) |
また、呼び出し可能オブジェクトに渡される引数は 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()
照合順序を取り除くには create_collation を callable とし
て None を渡して呼び出します:
con.create_collation("reverse", None)
| ) |
| authorizer_callback) |
コールバックの第一引数はどの種類の操作が許可されるかを決めます。第二第 三引数には第一引数に依存して本当に使われる引数か None かが渡 されます。第四引数はもし適用されるならばデータベースの名前("main", "temp", etc.)です。第五引数はアクセスを試みる要因となった最も内側のトリ ガまたはビューの名前、またはアクセスの試みが入力された SQL コードに直接 起因するものならば None です。
第一引数に与えることができる値や、その第一引数によって決まる第二第三引 数の意味については、SQLite の文書を参考にしてください。必要な定数は全 て sqlite3 モジュールに用意されています。
例:
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"]
タプルを返すのでは物足りず、名前に基づいたカラムへのアクセスが行ない たい場合は、高度に最適化された sqlite3.Row 型を row_factory にセットすることを考えてはいかがでしょうか。 Row クラスでは添字でも大文字小文字を無視した名前でもカラムに アクセスでき、しかもほとんどメモリーを浪費しません。 おそらく、辞書を使うような独自実装のアプローチよりも、もしか すると db の行に基づいた解法よりも良いものかもしれません。
効率の問題を考えて、非ASCIIデータに限って Unicode オブジェクトを返し、 その他の場合にはバイト列を返す方法もあります。これを有効にしたければ、 この属性を sqlite3.OptimizedUnicode に設定してください。
バイト列を受け取って望みの型のオブジェクトを返すような呼び出し可能オブジェクトを 何でも設定して構いません。
以下の説明用のコード例を参照してください:
import sqlite3
con = sqlite3.connect(":memory:")
cur = con.cursor()
# Create the table
con.execute("create table person(lastname, firstname)")
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 pysqlite always return bytestrings ...
con.text_factory = str
cur.execute("select ?", (AUSTRIA,))
row = cur.fetchone()
assert type(row[0]) == 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]) == unicode
# pysqlite offers a builtin 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]) == unicode
cur.execute("select ?", ("Germany",))
row = cur.fetchone()
assert type(row[0]) == str
ご意見やご指摘をお寄せになりたい方は、 このドキュメントについて... をご覧ください。