text_factory.py 768 Bytes
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
import sqlite3

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

AUSTRIA = "\xd6sterreich"

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

13
# but we can make sqlite3 always return bytestrings ...
14
con.text_factory = bytes
15 16
cur.execute("select ?", (AUSTRIA,))
row = cur.fetchone()
17
assert type(row[0]) is bytes
18 19 20 21 22
# 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 ...
23 24 25
# here we implement one that appends "foo" to all strings
con.text_factory = lambda x: x.decode("utf-8") + "foo"
cur.execute("select ?", ("bar",))
26
row = cur.fetchone()
27
assert row[0] == "barfoo"