PageRenderTime 41ms CodeModel.GetById 20ms app.highlight 4ms RepoModel.GetById 16ms app.codeStats 0ms

/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
 1import sqlite3
 2
 3class Point(object):
 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
10def adapt_point(point):
11    return "%f;%f" % (point.x, point.y)
12
13def convert_point(s):
14    x, y = map(float, s.split(";"))
15    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()