import sqlite3
import numpy as np
def convert_int(x):
print('convert_int was called with {}'.format(x))
if x == b'None' or x == b'':
return -1 # minus 1 as placeholder for integer nan
return np.int64(np.float64(x)) # np.float64 needed here as int(b'4.0') throws
sqlite3.register_converter('int', convert_int)
sqlite3.register_converter('None', convert_int) # attempt to tigger upon None
sqlite3.register_converter('NoneType', convert_int) # attempt to tigger upon None
sqlite3.register_converter('null', convert_int) # attempt to tigger upon None
values = [(4.0,), (4,), (None,), ('',), (1.0,)] #
conn = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)
conn.execute("create table test(p int)")
conn.executemany("insert into test(p) values (?)", values)
print(list(conn.execute("select p from test")))
产生以下输出:
convert_int was called with b'4'
convert_int was called with b'4'
convert_int was called with b'1'
Out[2]:
[(4,), (4,), (None,), (None,), (1,)] #
对于非None类型的条目,convert\u int()只被调用3次? 为了将其他2个None类型转换/解析为其他值,我需要注册什么样的转换器? 不幸的是,我上面的尝试不起作用。你知道吗
这就是the ^{} function in Modules/_sqlite/cursor.c 如何处理要转换的值:
^{} function 为SQL
NULL
值返回NULL
;在本例中,if (!val_str)
分支返回None
值而不调用转换器。你知道吗因此不可能将空值转换为其他值。你知道吗
转换器旨在添加对其他数据类型的支持。如果要获取实际不在数据库中的值,请更改查询:
(如果没有空表列,这也需要
PARSE_COLNAMES
。)相关问题 更多 >
编程相关推荐