Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | import sqlite3 |
| 2 | |
Éric Araujo | 28053fb | 2010-11-22 03:09:19 +0000 | [diff] [blame] | 3 | class Point: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4 | def __init__(self, x, y): |
| 5 | self.x, self.y = x, y |
| 6 | |
| 7 | def __repr__(self): |
| 8 | return "(%f;%f)" % (self.x, self.y) |
| 9 | |
| 10 | def adapt_point(point): |
Petri Lehtinen | 1ca9395 | 2012-02-15 22:17:21 +0200 | [diff] [blame] | 11 | return ("%f;%f" % (point.x, point.y)).encode('ascii') |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 12 | |
| 13 | def convert_point(s): |
Petri Lehtinen | 1ca9395 | 2012-02-15 22:17:21 +0200 | [diff] [blame] | 14 | x, y = list(map(float, s.split(b";"))) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 15 | return Point(x, y) |
| 16 | |
| 17 | # Register the adapter |
| 18 | sqlite3.register_adapter(Point, adapt_point) |
| 19 | |
| 20 | # Register the converter |
| 21 | sqlite3.register_converter("point", convert_point) |
| 22 | |
| 23 | p = Point(4.0, -3.2) |
| 24 | |
| 25 | ######################### |
| 26 | # 1) Using declared types |
| 27 | con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES) |
| 28 | cur = con.cursor() |
| 29 | cur.execute("create table test(p point)") |
| 30 | |
| 31 | cur.execute("insert into test(p) values (?)", (p,)) |
| 32 | cur.execute("select p from test") |
| 33 | print("with declared types:", cur.fetchone()[0]) |
| 34 | cur.close() |
| 35 | con.close() |
| 36 | |
| 37 | ####################### |
| 38 | # 1) Using column names |
| 39 | con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES) |
| 40 | cur = con.cursor() |
| 41 | cur.execute("create table test(p)") |
| 42 | |
| 43 | cur.execute("insert into test(p) values (?)", (p,)) |
| 44 | cur.execute('select p as "p [point]" from test') |
| 45 | print("with column names:", cur.fetchone()[0]) |
| 46 | cur.close() |
| 47 | con.close() |