插入多个值时出现Sqlite错误

时间:2021-07-02 07:02:14

标签: python sqlite

Code

error

当我尝试运行这个 python 文件时,我在 git-bash 终端上看到以下错误:

$ python database_insert_many.py
Traceback (most recent call last):
  File "E:\AutomationTesting\SQL_Database_Practise\SQlite3_Practice\database_insert_many.py", line 19, in <module>
    c.execute("INSERT INTO customers('first_name','last_name','email') VALUES (?,?,?)", str(many_customers))
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 3, and there are 103 supplied.

2 个答案:

答案 0 :(得分:0)

在sqlite中插入多条记录,需要运行类似这样的代码

import sqlite3

conn = sqlite3.connect('example.db')
cursor = conn.cursor()

records = [(1, 'Glen', 8),
            (2, 'Elliot', 9),
            (3, 'Bob', 7)]

cursor.executemany('INSERT INTO students VALUES(?,?,?);',records)

conn.commit()
#close the connection
conn.close()

有关详细信息,请参阅 this 教程

答案 1 :(得分:0)

错误信息是明确的。你的插入语句

"INSERT INTO customers('first_name','last_name','email') VALUES (?,?,?)"

包含 3 个 ?,因此需要 3 个值。这意味着 execute 参数应该是 3 个值的序列,例如 ('John', 'Doe', 'John.Doe@example.com')。而不是传递一个字符串 (str(many_customers)),它恰好是 103 个字符长。

在这里,您尝试同时插入 3 个元组。这意味着您应该使用 executemany:

c.executemany("INSERT INTO customers('first_name','last_name','email') VALUES (?,?,?)",
              many_customers)
相关问题