SQLite executemany 要求比预期更多的值

SQLite executemany asking for more values than expected

我正在尝试使用 SQLite 将列表插入到数据库中,第一个值是带有 AUTOINCREMENT 属性 的 ID。这是代码:

# cursor.execute('''
#    CREATE TABLE products (
#        prod_id INTEGER PRIMARY KEY AUTOINCREMENT,
#        prod_name VARCHAR(20),
#        prod_brand VARCHAR(20),
#        price FLOAT
#    )
# ''')

products = [
    ('Keyboard', 'Doctor Key', 20.0),
    ('Mouse', 'MasterClick', 2.50)
]

cursor.executemany("INSERT INTO products VALUES (null,?,?,?), products")

我也试过这样做:

cursor.executemany("INSERT INTO products (prod_id,prod_name,prod_brand,price) VALUES (null,?,?,?),productos")

但是在这两种情况下我都得到了同样的错误:

 Traceback (most recent call last):
          File "leccion2-1.py", line 38, in <module>
            cursor.executemany("INSERT INTO products VALUES (null,?,?,?), products") 
TypeError: function takes exactly 2 arguments (1 given)

This answer 对我不起作用。

谢谢。

您需要在引号之外提供值,因为您传递的是变量,而不是字符串。

cursor.executemany("INSERT INTO products VALUES (null,?,?,?)", products)

另请参阅此 example

import sqlite3
con = sqlite3.connect("samples.db")
cur = con.cursor()

examples = [(2, "def"), (3, "ghi"), (4, "jkl")]
cur.executemany("INSERT INTO samples VALUES (?, ?)", examples)

for row in cur.execute("SELECT * FROM samples"):
    print row