|
3 | 3 | con = sqlite3.connect(":memory:") |
4 | 4 | cur = con.cursor() |
5 | 5 |
|
6 | | -# Create the table |
7 | | -con.execute("create table person(lastname, firstname)") |
8 | | - |
9 | 6 | AUSTRIA = "\xd6sterreich" |
10 | 7 |
|
11 | 8 | # by default, rows are returned as Unicode |
|
14 | 11 | assert row[0] == AUSTRIA |
15 | 12 |
|
16 | 13 | # but we can make sqlite3 always return bytestrings ... |
17 | | -con.text_factory = str |
| 14 | +con.text_factory = bytes |
18 | 15 | cur.execute("select ?", (AUSTRIA,)) |
19 | 16 | row = cur.fetchone() |
20 | | -assert type(row[0]) == str |
| 17 | +assert type(row[0]) is bytes |
21 | 18 | # the bytestrings will be encoded in UTF-8, unless you stored garbage in the |
22 | 19 | # database ... |
23 | 20 | assert row[0] == AUSTRIA.encode("utf-8") |
24 | 21 |
|
25 | 22 | # 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 |
28 | | -con.text_factory = lambda x: str(x, "utf-8", "ignore") |
29 | | -cur.execute("select ?", ("this is latin1 and would normally create errors" + |
30 | | - "\xe4\xf6\xfc".encode("latin1"),)) |
31 | | -row = cur.fetchone() |
32 | | -assert type(row[0]) == str |
33 | | - |
34 | | -# sqlite3 offers a built-in optimized text_factory that will return bytestring |
35 | | -# objects, if the data is in ASCII only, and otherwise return unicode objects |
36 | | -con.text_factory = sqlite3.OptimizedUnicode |
37 | | -cur.execute("select ?", (AUSTRIA,)) |
38 | | -row = cur.fetchone() |
39 | | -assert type(row[0]) == str |
40 | | - |
41 | | -cur.execute("select ?", ("Germany",)) |
| 23 | +# here we implement one that appends "foo" to all strings |
| 24 | +con.text_factory = lambda x: x.decode("utf-8") + "foo" |
| 25 | +cur.execute("select ?", ("bar",)) |
42 | 26 | row = cur.fetchone() |
43 | | -assert type(row[0]) == str |
| 27 | +assert row[0] == "barfoo" |
0 commit comments