/Doc/includes/sqlite3/converter_point.py

http://unladen-swallow.googlecode.com/ · Python · 47 lines · 30 code · 11 blank · 6 comment · 0 complexity · 85db6ee667a2fdb55179caaca2ac3d0e MD5 · raw file

  1. import sqlite3
  2. class Point(object):
  3. def __init__(self, x, y):
  4. self.x, self.y = x, y
  5. def __repr__(self):
  6. return "(%f;%f)" % (self.x, self.y)
  7. def adapt_point(point):
  8. return "%f;%f" % (point.x, point.y)
  9. def convert_point(s):
  10. x, y = map(float, s.split(";"))
  11. return Point(x, y)
  12. # Register the adapter
  13. sqlite3.register_adapter(Point, adapt_point)
  14. # Register the converter
  15. sqlite3.register_converter("point", convert_point)
  16. p = Point(4.0, -3.2)
  17. #########################
  18. # 1) Using declared types
  19. con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)
  20. cur = con.cursor()
  21. cur.execute("create table test(p point)")
  22. cur.execute("insert into test(p) values (?)", (p,))
  23. cur.execute("select p from test")
  24. print "with declared types:", cur.fetchone()[0]
  25. cur.close()
  26. con.close()
  27. #######################
  28. # 1) Using column names
  29. con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES)
  30. cur = con.cursor()
  31. cur.execute("create table test(p)")
  32. cur.execute("insert into test(p) values (?)", (p,))
  33. cur.execute('select p as "p [point]" from test')
  34. print "with column names:", cur.fetchone()[0]
  35. cur.close()
  36. con.close()