令人困惑的SQLite3错误

时间:2018-08-05 12:55:52

标签: python python-3.x sqlite

我已经使用SQLite3在python中建立了一个数据库,并尝试添加一些数据,但是当前收到错误You did not supply a value for binding 1.。香港专业教育学院作出了完全相同的数据库(具有不同的值)之前,但没有得到此错误,我在这里做错了吗?

这是错误的数据库:

def Add_User_Data(self):
        self.c.execute("INSERT INTO Employees VALUES (:ID, :FirstName, :Surname, :DOB, :Age, :Gender)",
                     {'ID: ': self.AddEmployee.ID.get(), 'FirstName: ':self.AddEmployee.FirstName.get(), 'Surname: ':self.AddEmployee.Surname.get(),
                     'DOB: ':self.AddEmployee.DOB.get(), 'Age: ':self.AddEmployee.Age.get(), 'Gender: ':self.AddEmployee.Gender.get()})


        self.conn.commit()

这是没有出错的旧版本。

def addEmployees(self):
        self.c.execute("INSERT INTO Employees VALUES (:FirstName, :Surname, :Age, :Postcode, :Wage, :Email, :Hours)",
                     {'FirstName': 'aa', 'Surname':"Jan" , 'Age':"21" ,
                     'Postcode':"UB5 7T3" , 'Wage':"1220000" , 'Email':"s@gmail.com" , 'Hours':"230"})

        self.conn.commit()

-------------------------------------------------- ---------回答---------------------------------------- ------------------------

所以我通过将布局更改为此来解决了这个问题,并且有效:

self.params = (self.AddEmployee.ID.get(), self.AddEmployee.FirstName.get(), self.AddEmployee.Surname.get(),
        self.AddEmployee.DOB.get(), self.AddEmployee.Age.get(), self.AddEmployee.Gender.get())

        self.c.execute("INSERT INTO Employees VALUES (?, ?, ?, ?, ?, ? )", self.params)

        self.conn.commit()

我在以下位置找到了解决方案:sqlite3.OperationalError: no such column:

感谢所有回答并尝试提供帮助的人!

1 个答案:

答案 0 :(得分:0)

对于docs所示的未来读者来说,Python sqlite3 DB-API支持 qmark named 样式进行参数化。 OP使用 qmark 样式解决了问题。但是,OP的原始尝试确实可以通过适当的字典键分配来工作,其中字典键与指定的参数完全对应。

具体来说,由于字典键中的冒号和空格,以下字典将无法绑定到命名参数(:ID, :FirstName, :Surname, ...):

{'ID: ': self.AddEmployee.ID.get(), 
 'FirstName: ':self.AddEmployee.FirstName.get(), 
 'Surname: ':self.AddEmployee.Surname.get(),
 'DOB: ':self.AddEmployee.DOB.get(), 
 'Age: ':self.AddEmployee.Age.get(), 
 'Gender: ':self.AddEmployee.Gender.get()}

但是,以下内容应适用于相同的准备好的SQL语句:

{'ID': self.AddEmployee.ID.get(), 
 'FirstName': self.AddEmployee.FirstName.get(), 
 'Surname': self.AddEmployee.Surname.get(),
 'DOB': self.AddEmployee.DOB.get(), 
 'Age': self.AddEmployee.Age.get(), 
 'Gender': self.AddEmployee.Gender.get()}

一起,用于光标调用:

self.sql = "INSERT INTO Employees VALUES (:ID, :FirstName, :Surname, :DOB, :Age, :Gender)"

self.qparams = {'ID': self.AddEmployee.ID.get(), 
                'FirstName': self.AddEmployee.FirstName.get(), 
                'Surname': self.AddEmployee.Surname.get(),
                'DOB': self.AddEmployee.DOB.get(), 
                'Age': self.AddEmployee.Age.get(), 
                'Gender': self.AddEmployee.Gender.get()}

self.c.execute(self.sql, self.qparams)
self.conn.commit()