1 import sqlite3 2 3 con = sqlite3.connect(":memory:") 4 cur = con.cursor() 5 6 AUSTRIA = u"\xd6sterreich" 7 8 # by default, rows are returned as Unicode 9 cur.execute("select ?", (AUSTRIA,)) 10 row = cur.fetchone() 11 assert row[0] == AUSTRIA 12 13 # but we can make sqlite3 always return bytestrings ... 14 con.text_factory = str 15 cur.execute("select ?", (AUSTRIA,)) 16 row = cur.fetchone() 17 assert type(row[0]) is str 18 # the bytestrings will be encoded in UTF-8, unless you stored garbage in the 19 # database ... 20 assert row[0] == AUSTRIA.encode("utf-8") 21 22 # we can also implement a custom text_factory ... 23 # here we implement one that will ignore Unicode characters that cannot be 24 # decoded from UTF-8 25 con.text_factory = lambda x: unicode(x, "utf-8", "ignore") 26 cur.execute("select ?", ("this is latin1 and would normally create errors" + 27 u"\xe4\xf6\xfc".encode("latin1"),)) 28 row = cur.fetchone() 29 assert type(row[0]) is unicode 30 31 # sqlite3 offers a built-in optimized text_factory that will return bytestring 32 # objects, if the data is in ASCII only, and otherwise return unicode objects 33 con.text_factory = sqlite3.OptimizedUnicode 34 cur.execute("select ?", (AUSTRIA,)) 35 row = cur.fetchone() 36 assert type(row[0]) is unicode 37 38 cur.execute("select ?", ("Germany",)) 39 row = cur.fetchone() 40 assert type(row[0]) is str 41