我在Python中使用sqlite3查询了一个SQL数据库,并创建了一个名为FOOBAR的自定义数据类型。具有此数据类型的列存储一个字符串,该字符串是文件路径。当查询时,转换器打开文件并返回一些数据,这些数据运行良好。
我想知道是否有任何方法可以将文件路径字符串从列中提取出来,也就是说,有时不为这种自定义数据类型选择性地应用转换器。
发布于 2016-03-03 13:38:46
如果在转换中使用挂钩的 method,请使用CAST“更改”列的类型:
select CAST(filename as TEXT) from table where <filter>这会导致SQLite报告文件名具有不同类型(在本例中为文本),从而绕过与列关联的类型转换。
演示,改编自 example from the documentation
>>> import sqlite3
>>> class Point(object):
... def __init__(self, x, y):
... self.x, self.y = x, y
... def __repr__(self):
... return "Point(%f, %f)" % (self.x, self.y)
...
>>> def adapt_point(point):
... return "%f;%f" % (point.x, point.y)
...
>>> def convert_point(s):
... return Point(*(float(c) for c in s.split(";")))
...
>>> sqlite3.register_adapter(Point, adapt_point)
>>> sqlite3.register_converter("point", convert_point)
>>> p = Point(4.0, -3.2)
>>> con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)
>>> cur = con.cursor()
>>> cur.execute("create table test(p point)")
<sqlite3.Cursor object at 0x105d03650>
>>> cur.execute("insert into test(p) values (?)", (p,))
<sqlite3.Cursor object at 0x105d03650>
>>> cur.execute("select p from test").fetchone()[0]
Point(4.000000, -3.200000)
>>> cur.execute("select cast(p as text) from test").fetchone()[0]
u'4.000000;-3.200000'如果您使用的是 method,那么在查询时不要在列名别名中包含类型。
https://stackoverflow.com/questions/35490357
复制相似问题