【发布时间】:2015-11-11 19:19:29
【问题描述】:
我有一个通过 Python 代码创建的名为“test”的表。
db = sqlite3.connect("mydb.db")
cur = db.cursor()
cur.execute('''CREATE TABLE IF NOT EXISTS test
(
"id" text primary key,
"field1" integer,
"fiedl2" integer,
"field3" text
)'''
)
我有一个文件,其中每一行都是一个 json。我逐行读取文件并将每行的json中的数据插入表中。
文件.txt:
{'id':'abcde', 'field1': 10, 'field2': 20, 'field3': "hello"}
{'id':'asdf', 'field1': 20, 'field2': 5, 'field3': "world"}
{'id':'qwerty', 'field1': 1, 'field2': 2, 'field3': None}
如果 json 中的字段没有值,我想将 null 插入到我的 sqlite 表中。所以和上面最后一行一样,如果 field3 没有值,我把 None 放进去,因为这是我在其他相关问题中读到的。
但是,当我插入如下:
for line in readfile:
line = ast.literal_eval(line)
columns = '", "'.join([i.strip() for i in line.keys()])
columns = "\"" + columns + '\"'
placeholders = ', '.join('?' * len(line))
sql = 'INSERT INTO test ({}) VALUES ({})'.format(columns, placeholders)
cur.execute(sql, ["'" + str(i) + "'" for i in line.values()])
db.commit()
当我从 Sqlite 控制台执行 select 语句时,我得到 'None' 而不是 null。
sqlite> select * from test where id='qwerty' limit 1;
'qwerty'|1|2|'None'|
谁能帮我解决这个问题?我正在使用 Python 3.4
【问题讨论】:
-
您是否考虑过测试一个值是否为
None?