【问题标题】:SQLite executemany asking for more values than expectedSQLite executemany 要求比预期更多的值
【发布时间】:2021-01-25 04:14:19
【问题描述】:

我正在尝试使用 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 对我不起作用。

谢谢。

【问题讨论】:

    标签: python sqlite auto-increment executemany


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2015-10-14
      • 2013-12-19
      • 2017-02-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多