blob: 5df828e3361246fb57d5f891d3327fa7c08532e3 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001import sqlite3
2
Éric Araujo28053fb2010-11-22 03:09:19 +00003class Point:
Georg Brandl116aa622007-08-15 14:28:22 +00004 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
10def adapt_point(point):
Petri Lehtinen1ca93952012-02-15 22:17:21 +020011 return ("%f;%f" % (point.x, point.y)).encode('ascii')
Georg Brandl116aa622007-08-15 14:28:22 +000012
13def convert_point(s):
Petri Lehtinen1ca93952012-02-15 22:17:21 +020014 x, y = list(map(float, s.split(b";")))
Georg Brandl116aa622007-08-15 14:28:22 +000015 return Point(x, y)
16
17# Register the adapter
18sqlite3.register_adapter(Point, adapt_point)
19
20# Register the converter
21sqlite3.register_converter("point", convert_point)
22
23p = Point(4.0, -3.2)
24
25#########################
26# 1) Using declared types
27con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)
28cur = con.cursor()
29cur.execute("create table test(p point)")
30
31cur.execute("insert into test(p) values (?)", (p,))
32cur.execute("select p from test")
33print("with declared types:", cur.fetchone()[0])
34cur.close()
35con.close()
36
37#######################
38# 1) Using column names
39con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES)
40cur = con.cursor()
41cur.execute("create table test(p)")
42
43cur.execute("insert into test(p) values (?)", (p,))
44cur.execute('select p as "p [point]" from test')
45print("with column names:", cur.fetchone()[0])
46cur.close()
47con.close()