/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

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