cpython/Doc/includes/sqlite3/text_factory.py

30 lines
781 B
Python
Raw Normal View History

2007-08-15 11:28:22 -03:00
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
# but we can make sqlite3 always return bytestrings ...
con.text_factory = bytes
2007-08-15 11:28:22 -03:00
cur.execute("select ?", (AUSTRIA,))
row = cur.fetchone()
assert type(row[0]) is bytes
2007-08-15 11:28:22 -03:00
# 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 appends "foo" to all strings
con.text_factory = lambda x: x.decode("utf-8") + "foo"
cur.execute("select ?", ("bar",))
2007-08-15 11:28:22 -03:00
row = cur.fetchone()
assert row[0] == "barfoo"
con.close()