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