【问题标题】:Insert null into Sqlite from Python从 Python 将 null 插入 Sqlite
【发布时间】: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

标签: python json sqlite


【解决方案1】:

您将得到一个 "None" 字符串,因为您在将 None 转换为字符串之前将其传递给 execute 函数:

cur.execute(sql, ["'" + str(i) + "'" for i in line.values()])

因此,就 python/sqlite 而言,您插入的是字符串 "None" - 而不是 None 对象。

将参数作为execute 函数中的第二个参数的意义在于,它应该为您执行值到sql 字符串的表示。因此,您应该在它们的原生 python 数据类型中提供值。

所以,使用

cur.execute(sql, list(line.values()))

实际上应该给你一个null而不是"None"

【讨论】:

  • 完美运行!我不得不使用 cur.execute(sql, list(line.values()) 虽然
  • 对-那是因为您使用的是python3,其中值作为迭代器返回-我错过了。我相应地编辑了我的答案。
猜你喜欢
  • 2013-06-14
  • 1970-01-01
  • 2020-02-20
  • 1970-01-01
  • 2012-02-07
  • 2012-06-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多