PageRenderTime 8ms CodeModel.GetById 2ms app.highlight 4ms RepoModel.GetById 1ms app.codeStats 0ms

/Doc/includes/sqlite3/text_factory.py

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