1import sqlite3
2
3con = sqlite3.connect(":memory:")
4cur = con.cursor()
5
6AUSTRIA = "\xd6sterreich"
7
8# by default, rows are returned as Unicode
9cur.execute("select ?", (AUSTRIA,))
10row = cur.fetchone()
11assert row[0] == AUSTRIA
12
13# but we can make sqlite3 always return bytestrings ...
14con.text_factory = bytes
15cur.execute("select ?", (AUSTRIA,))
16row = cur.fetchone()
17assert type(row[0]) is bytes
18# the bytestrings will be encoded in UTF-8, unless you stored garbage in the
19# database ...
20assert row[0] == AUSTRIA.encode("utf-8")
21
22# we can also implement a custom text_factory ...
23# here we implement one that appends "foo" to all strings
24con.text_factory = lambda x: x.decode("utf-8") + "foo"
25cur.execute("select ?", ("bar",))
26row = cur.fetchone()
27assert row[0] == "barfoo"
28