【发布时间】:2017-05-04 21:44:06
【问题描述】:
我正在尝试在 Python 中使用 executemany 来填充一些行。
但是,我得到:
sqlite3.OperationalError: 3 values for 4 columns
我了解,一般来说,您使用executemany 尽可能高效地将原始值填充到数据库中,考虑到这一点,您通常希望插入的值的数量与列数相匹配。
但是如果一个或多个列是通过 SQL “构造”的,并且没有任何对应的输入值呢?
小例子:
#!/usr/bin/env python2.7
import os
import sys
import sqlite3
from contextlib import closing
DB_FILE = 'test.sqlite'
with closing(sqlite3.connect(DB_FILE)) as db:
# First, some setup...
cursor = db.cursor()
cursor.execute('CREATE TABLE test (id TEXT PRIMARY KEY, a TEXT, b TEXT, c TEXT)')
sql = '''INSERT INTO test (id, a, b, c) VALUES (?, ?, ?, ?)'''
data = []
for i in range(5):
idStr = str(i)
data.append( (idStr, 'a{}'.format(i), 'b{}'.format(i), 'c{}'.format(i)) )
cursor.executemany(sql, data)
# Now, to exercise the problem:
# This does an 'upsert', but the same problem could occur in
# other circumstances.
sql = '''
INSERT OR REPLACE INTO test (id, a, b, c)
VALUES (
?,
(SELECT a,b FROM test WHERE id = ?),
?
)'''
data = []
for i in range(3,7):
idStr = str(i)
data.append( (idStr, idStr, 'c{}'.format(i)) )
cursor.executemany(sql, data)
db.commit()
当您运行它时,您会收到顶部提到的错误 (3 values for 4 columns)。
我想我可以通过将 SELECT a,b 拆分为单独的 SELECT a..., SELECT b... 部分来解决此问题,但有更好的方法吗?
给出的示例很小 — 实际上,它可能是 10 列,我现在必须详细列出它们自己的 (SELECT ...) 子句。
更新 1 这不是 executemany 特有的,正如我最初所想的那样。即使手动运行纯 SQL 也有同样的问题。
更新 2 下面的答案建议使用 SELECT 而不是 VALUES,但是,在添加新行时这不起作用(如在我的“upsert”案例中),因为SELECT 在这种情况下不返回任何行。
【问题讨论】:
标签: python sqlite executemany