mirror of
https://github.com/python/cpython.git
synced 2025-08-04 00:48:58 +00:00
Issue #13491: Fix many errors in sqlite3 documentation
Initial patch by Johannes Vogel.
This commit is contained in:
parent
2640b52237
commit
1ca93954e1
10 changed files with 29 additions and 52 deletions
|
@ -3,9 +3,6 @@ import sqlite3
|
|||
con = sqlite3.connect(":memory:")
|
||||
cur = con.cursor()
|
||||
|
||||
# Create the table
|
||||
con.execute("create table person(lastname, firstname)")
|
||||
|
||||
AUSTRIA = "\xd6sterreich"
|
||||
|
||||
# by default, rows are returned as Unicode
|
||||
|
@ -14,30 +11,17 @@ row = cur.fetchone()
|
|||
assert row[0] == AUSTRIA
|
||||
|
||||
# but we can make sqlite3 always return bytestrings ...
|
||||
con.text_factory = str
|
||||
con.text_factory = bytes
|
||||
cur.execute("select ?", (AUSTRIA,))
|
||||
row = cur.fetchone()
|
||||
assert type(row[0]) == str
|
||||
assert type(row[0]) is bytes
|
||||
# the bytestrings will be encoded in UTF-8, unless you stored garbage in the
|
||||
# database ...
|
||||
assert row[0] == AUSTRIA.encode("utf-8")
|
||||
|
||||
# we can also implement a custom text_factory ...
|
||||
# here we implement one that will ignore Unicode characters that cannot be
|
||||
# decoded from UTF-8
|
||||
con.text_factory = lambda x: str(x, "utf-8", "ignore")
|
||||
cur.execute("select ?", ("this is latin1 and would normally create errors" +
|
||||
"\xe4\xf6\xfc".encode("latin1"),))
|
||||
# here we implement one that appends "foo" to all strings
|
||||
con.text_factory = lambda x: x.decode("utf-8") + "foo"
|
||||
cur.execute("select ?", ("bar",))
|
||||
row = cur.fetchone()
|
||||
assert type(row[0]) == str
|
||||
|
||||
# sqlite3 offers a built-in optimized text_factory that will return bytestring
|
||||
# objects, if the data is in ASCII only, and otherwise return unicode objects
|
||||
con.text_factory = sqlite3.OptimizedUnicode
|
||||
cur.execute("select ?", (AUSTRIA,))
|
||||
row = cur.fetchone()
|
||||
assert type(row[0]) == str
|
||||
|
||||
cur.execute("select ?", ("Germany",))
|
||||
row = cur.fetchone()
|
||||
assert type(row[0]) == str
|
||||
assert row[0] == "barfoo"
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue