在Python中将Null插入SQLite3

moe*_*sef 12 python sqlite sql-insert

我试图将None值插入我的数据库的行条目.该表present存在

db.execute("INSERT INTO present VALUES('test', ?, 9)", "This is a test!")
db.execute("INSERT INTO present VALUES('test2', ?, 10)", None)
Run Code Online (Sandbox Code Playgroud)

但是我收到一个错误:

ValueError: parameters are of unsupported type
Run Code Online (Sandbox Code Playgroud)

如何为行中的第二个字段插入空白值?

Tim*_*der 25

使用元组,IE:

db.execute("INSERT INTO present VALUES('test2', ?, 10)", (None,))
Run Code Online (Sandbox Code Playgroud)


小智 5

上次测试时间:2018 年 8 月

  • 蟒蛇 3.6.1
  • 蟒蛇 2.7.10

我不确定发布原始问题时是否是这种情况,但截至今天:

db.execute("INSERT INTO present VALUES('test', ?, 9)", "This is a test!")
Run Code Online (Sandbox Code Playgroud)

投掷

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 15 supplied.
Run Code Online (Sandbox Code Playgroud)

跑的时候。

因为execute()接受sql——这是要执行的 sql 查询,并且parameters——它是可迭代的,包含查询参数(目前这对Python 2Python 3都是如此。由于字符串是可迭代的——它会相应地对待它。

文档明确指出,PythonNone类型对应于 SQLiteNULL类型。

所以,正确的做法是:

db.execute("INSERT INTO present VALUES('test2', :null, 10)", {'null':None})

#or

db.execute("INSERT INTO present VALUES('test2', ?, 10)", (None,))
Run Code Online (Sandbox Code Playgroud)