Python's Archiver

為方便港臺同胞閱覽,Python中國特別推出簡繁體內容轉換功能

zkfarmer 发表于 2008-10-25 23:07

13.13.4.3 转换SQLite值为自定义的Python类型

编写一个适配器使得你传递Python类型给SQLite。但是真正有用的,我们需要是Python到SQLite到Python来回工作。

进入转换。

让我们回到Point类。在SQLite中我们存储由分号隔开的x和y坐标。

首先,我们定义一个转换函数,接受一个字符串参数并从中构造一个Point对象。

注意:转换函数始终以一个字符串调用,不论从属(你传递给SQLite的值的数据类型)。

注意:转换名称被查询用一种区分大小写的方式。
    def convert_point(s):
        x, y = map(float, s.split(";"))
        return Point(x, y)

现在你需要使sqlite3模块知道你从数据库中选择的实际是一个点。有两种方法做到这点:
•        通过隐含地声明的类型
•        通过明确地列名称。

讲述的两种方法在13.13.1节“模块常量”中,常量PARSE_DECLTYPES和PARSE_COLNAMES项。

下面的例子说明两种方法。
import sqlite3

class Point(object):
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __repr__(self):
        return "(%f;%f)" % (self.x, self.y)

def adapt_point(point):
    return "%f;%f" % (point.x, point.y)

def convert_point(s):
    x, y = map(float, s.split(";"))
    return Point(x, y)

# Register the adapter
sqlite3.register_adapter(Point, adapt_point)

# Register the converter
sqlite3.register_converter("point", convert_point)

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.execute("insert into test(p) values (?)", (p,))
cur.execute("select p from test")
print "with declared types:", cur.fetchone()[0]
cur.close()
con.close()

#######################
# 1) Using column names
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES)
cur = con.cursor()
cur.execute("create table test(p)")

cur.execute("insert into test(p) values (?)", (p,))
cur.execute('select p as "p [point]" from test')
print "with column names:", cur.fetchone()[0]
cur.close()
con.close()

作为文本下载(原文件名:sqlite3/converter_point.py)。

出处[url=http://www.okpython.com]PYTHON中国[/url],关于翻译的任何事情请EMAIL给我[email=zkfarmer@gmail.com]zkfarmer[/email],更多文档在[url=http://www.zkfarmer.org]我的站点[/url],[color=Red]请参阅官方英文文档[/color]。

[[i] 本帖最后由 zkfarmer 于 2008-10-25 23:10 编辑 [/i]]

页: [1]

Powered by Discuz! Archiver 6.1.0  © 2001-2007 Comsenz Inc.