首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >选择性旁路数据型转换器

选择性旁路数据型转换器
EN

Stack Overflow用户
提问于 2016-02-18 19:10:39
回答 1查看 107关注 0票数 2

我在Python中使用sqlite3查询了一个SQL数据库,并创建了一个名为FOOBAR的自定义数据类型。具有此数据类型的列存储一个字符串,该字符串是文件路径。当查询时,转换器打开文件并返回一些数据,这些数据运行良好。

我想知道是否有任何方法可以将文件路径字符串从列中提取出来,也就是说,有时不为这种自定义数据类型选择性地应用转换器。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-03 13:38:46

如果在转换中使用挂钩的 method,请使用CAST“更改”列的类型:

代码语言:javascript
复制
select CAST(filename as TEXT) from table where <filter>

这会导致SQLite报告文件名具有不同类型(在本例中为文本),从而绕过与列关联的类型转换。

演示,改编自 example from the documentation

代码语言:javascript
复制
>>> 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,那么在查询时不要在列名别名中包含类型。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35490357

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档