我的一个A Level学生正在尝试让他们的代码在Python 3中工作,但它不断出现错误消息:“sqlite3.ProgrammingError:提供的绑定数量不正确。当前语句使用3,并且有1提供“。代码如下:
import sqlite3
def query(sql,data):
with sqlite3.connect("DogBreeds.db") as db:
cursor = db.cursor()
cursor.execute(sql,data)
db.commit()
def insert_dog_breed_data(records):
sql = "insert into DogBreed(Breed, Description, Previous_Litters) values (?,?,?)"
for record in records:
query(sql,record)
def insert_dog_data(records):
sql = "insert into Dogs (Name, Date of Birth, Gender, DogBreedID) values (?,?,?,?)"
for record in records:
query(sql,record)
if __name__ == "__main__":
dog_breeds = [("Shih Tzu",),("Jack Russell",),("Great Dane",),("Husky"("Cavalier King Charles Spaniel",),("Pug")]
insert_dog_breed_data(dog_breeds)
dogs = [("Steve", "10/08/2006", "Male",1),("John","08/05/2017", "Male",2),("Ellen", "25/12/2013","Female",3),("Betty", "13/01/2000", "Female",4),("Charlie", "30/03/2000", "Female",5),("Fred", "04/05/2000", "Male",5)]
insert_dog_data(dogs)
并且完整的错误消息是:
Traceback (most recent call last): File "G:\Dog Breeder Scenario - Python\Insert data 2.py", line 21, in <module> insert_dog_breed_data(dog_breeds) File "G:\Dog Breeder Scenario - Python\Insert data 2.py", line 12, in insert_dog_breed_data query(sql,record) File "G:\Dog Breeder Scenario - Python\Insert data 2.py", line 6, in query cursor.execute(sql,data) sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 3, and there are 1 supplied.
作为指南,他们遵循Python School网站的教程 - https://pythonschool.net/databases/inserting-data/
中的任务4任何帮助将不胜感激。 感谢。
答案 0 :(得分:1)
您将单项元组列表传递给insert_dog_breed_data
- 仅包含品种名称 - 但SQL查询需要三个项目 - 名称,描述,previous_litters。
注意,新程序员可以学习的最有用的技能之一是如何阅读错误消息。他们自己解决这个问题所需要的所有信息都在该信息中提供。
答案 1 :(得分:0)
问题是(正如@DanielRoseman解释的那样)sqlite
期望每个元组都包含 3 项目( Breed , Description , Previous_Litters )但您提供的只包含一个:
dog_breeds = [("Shih Tzu",),("Jack Russell",),("Great Dane",),("Husky"("Cavalier King Charles Spaniel",),("Pug")])
一种解决方案是修改dog_breeds
元组,然后将其传递给insert_dog_breed_data
函数,如下所示:
dog_breeds = [(x,) + ('', '') for x in dog_breeds]
假设您没有关于描述和 Previous_Litters 的信息。
将创建像这样的元组:("Shih Tzu", '', '')