0

我正在尝试使用 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)

这个答案对我不起作用。

谢谢。

4

1 回答 1

1

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

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

另请参阅此示例

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
于 2020-10-10T07:12:51.510 回答