当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python sqlite3.Connection.text_factory用法及代码示例


用法:

text_factory

使用此属性,您可以控制为 TEXT 数据类型返回的对象。默认情况下,此属性设置为 str 并且 sqlite3 模块将为 TEXT 返回 str 对象。如果您想返回 bytes ,可以将其设置为 bytes

您还可以将其设置为任何其他接受单个字节字符串参数并返回结果对象的可调用对象。

请参阅以下示例代码进行说明:

import sqlite3

con = sqlite3.connect(":memory:")
cur = con.cursor()

AUSTRIA = "Österreich"

# by default, rows are returned as str
cur.execute("select ?", (AUSTRIA,))
row = cur.fetchone()
assert row[0] == AUSTRIA

# but we can make sqlite3 always return bytestrings ...
con.text_factory = bytes
cur.execute("select ?", (AUSTRIA,))
row = cur.fetchone()
assert type(row[0]) is bytes
# the bytestrings will be encoded in UTF-8, unless you stored garbage in the
# database ...
assert row[0] == AUSTRIA.encode("utf-8")

# we can also implement a custom text_factory ...
# here we implement one that appends "foo" to all strings
con.text_factory = lambda x: x.decode("utf-8") + "foo"
cur.execute("select ?", ("bar",))
row = cur.fetchone()
assert row[0] == "barfoo"

con.close()

相关用法


注:本文由纯净天空筛选整理自python.org大神的英文原创作品 sqlite3.Connection.text_factory。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。