gh-90016: Reword sqlite3 adapter/converter docs (#93095)

Also add adapters and converter recipes.

Co-authored-by: CAM Gerlach <CAM.Gerlach@Gerlach.CAM>
Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com
This commit is contained in:
Erlend Egeberg Aasland 2022-06-25 22:06:06 +02:00 committed by GitHub
parent bec802dbb8
commit bd3c1c187e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 156 additions and 122 deletions

View file

@ -1,17 +0,0 @@
import sqlite3
import datetime
import time
def adapt_datetime(ts):
return time.mktime(ts.timetuple())
sqlite3.register_adapter(datetime.datetime, adapt_datetime)
con = sqlite3.connect(":memory:")
cur = con.cursor()
now = datetime.datetime.now()
cur.execute("select ?", (now,))
print(cur.fetchone()[0])
con.close()

View file

@ -5,28 +5,23 @@ class Point:
self.x, self.y = x, y
def __repr__(self):
return "(%f;%f)" % (self.x, self.y)
return f"Point({self.x}, {self.y})"
def adapt_point(point):
return ("%f;%f" % (point.x, point.y)).encode('ascii')
return f"{point.x};{point.y}".encode("utf-8")
def convert_point(s):
x, y = list(map(float, s.split(b";")))
return Point(x, y)
# Register the adapter
# Register the adapter and converter
sqlite3.register_adapter(Point, adapt_point)
# Register the converter
sqlite3.register_converter("point", convert_point)
# 1) Parse using declared types
p = Point(4.0, -3.2)
#########################
# 1) Using declared types
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)
cur = con.cursor()
cur.execute("create table test(p point)")
cur = con.execute("create table test(p point)")
cur.execute("insert into test(p) values (?)", (p,))
cur.execute("select p from test")
@ -34,11 +29,9 @@ print("with declared types:", cur.fetchone()[0])
cur.close()
con.close()
#######################
# 1) Using column names
# 2) Parse using column names
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES)
cur = con.cursor()
cur.execute("create table test(p)")
cur = con.execute("create table test(p)")
cur.execute("insert into test(p) values (?)", (p,))
cur.execute('select p as "p [point]" from test')