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