13.13.4.2 用适配器在SQLite数据库中存储附加的Python类型
之前描述的,SQLite自身仅支持一系列有限的类型。SQLite使用其它的Python类型,必须为SQLite改编它们为sqlite3模块支持的其中一种类型:None类型,int,long,float,str,unicode,buffer中的一种。sqlite3模块使用Python对象改编,描述在PEP246中。使用的协议是PrepareProtocol。
有两种方法能够使sqlite3模块改编一个自定义的Python类型为它支持的其中一种类型。
13.13.4.2.1 让你的对象改编自身
如果你自己编写类,这是一个好的门径。让我们假设你有这样一个类:
class Point(object):
def __init__(self, x, y):
self.x, self.y = x, y
现在你想要在一个单一的SQLite列中存储point。首先你将不得不选择支持的类型的其中一种用来表示point。让我们仅用str和分号分割坐标。然后你需要给你的类一个__conform__(self,protocol)方法,它必须返回转换的值。protocol参数是PrepareProtocol。
import sqlite3
class Point(object):
def __init__(self, x, y):
self.x, self.y = x, y
def __conform__(self, protocol):
if protocol is sqlite3.PrepareProtocol:
return "%f;%f" % (self.x, self.y)
con = sqlite3.connect(":memory:")
cur = con.cursor()
p = Point(4.0, -3.2)
cur.execute("select ?", (p,))
print cur.fetchone()[0]
作为文本下载(原文件名:sqlite3/adapter_point_1.py)。
13.13.4.2.2 注册一个适配器回调
其它的可能是创建一个函数转换该类型为字符串表示和用register_adapter注册的函数。
注意:转换的type/class必须是一个新类型的类,如,它必须有对象作为它的基类。
import sqlite3
class Point(object):
def __init__(self, x, y):
self.x, self.y = x, y
def adapt_point(point):
return "%f;%f" % (point.x, point.y)
sqlite3.register_adapter(Point, adapt_point)
con = sqlite3.connect(":memory:")
cur = con.cursor()
p = Point(4.0, -3.2)
cur.execute("select ?", (p,))
print cur.fetchone()[0]
作为文本下载(原文件名:sqlite3/adapter_point_2.py)。
对于Python的内置的datetime.date和datatime.datetime类型,sqlite3模块有两种缺省的适配器。现在让我们假设想要存储datetime.datetime对象不用ISO表示,而是作为Unix时间戳。
import sqlite3
import datetime, 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]
作为文本下载(原文件名:sqlite3/adapter_datetime.py)。
出处[url=http://www.okpython.com]PYTHON中国[/url],关于手册翻译的任何事情请EMAIL给我[email=zkfarmer@gmail.com]zkfarmer[/email],最新文档在我的[url=http://www.zkfarmer.org]site[/url],[color=Red]请参阅官方英文文档[/color]。
页:
[1]