3
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")))
產生以下輸出:sqlite - register_converters不觸發Python的NoneType?
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,)] #
convert_int()僅稱爲3次,非無型條目? 我需要註冊的轉換器是什麼,才能將其他2種類型轉換/解析爲某種替代值? 不幸的是我上面的嘗試不起作用。
非常感謝!這就結束了我的謎題,將按照建議使用IFNULL。 – kzk2000