我遇到了通过SQL将一些数据保存到数据库的问题。这段代码最初起作用了:
cnxn = pyodbc.connect('Driver={Microsoft Access Driver (*.mdb, *.accdb)}; Dbq=C:\\Users\\george\\Documents\\Homework\\Computing\\Monkey Studio\DrivingSchoolDatabase.accdb')
cursor = cnxn.cursor()
cursor.execute("insert into Students(Forename,Surname,Address1,Address2,PostCode,Home,Mobile,Email,License,Expiry,Medical,DOB,EyeTest) values (?,?,?,?,?,?,?,?,?,?,?,?,?)",forename,surname,address1,address2,postCode,homePhone,mobilePhone,email,license,expiry,medical,DOB,eyeTest)
cnxn.commit()
QtGui.QMessageBox.about(self, 'Saved','Student data saved')
self.close()
然后我在访问数据库中添加了两个新字段并将它们添加到代码中,所以我有了这个(两个新变量是先前和在哪里):
cnxn = pyodbc.connect('Driver={Microsoft Access Driver (*.mdb, *.accdb)}; Dbq=C:\\Users\\george\\Documents\\Homework\\Computing\\Monkey Studio\DrivingSchoolDatabase.accdb')
cursor = cnxn.cursor()
cursor.execute("insert into Students(Forename,Surname,Address1,Address2,PostCode,Home,Mobile,Email,License,Expiry,Medical,DOB,EyeTest,Previous,Where) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",forename,surname,address1,address2,postCode,homePhone,mobilePhone,email,license,expiry,medical,DOB,eyeTest,previous,where)
cnxn.commit()
QtGui.QMessageBox.about(self, 'Saved','Student data saved')
self.close()
我现在收到此错误:
Traceback (most recent call last):
File "C:\Users\george\Documents\Homework\Computing\Monkey Studio\AddAStudent.py", line 118, in AddCreateStu
cursor.execute("insert into Students(Forename,Surname,Address1,Address2,PostCode,Home,Mobile,Email,License,Expiry,Medical,DOB,EyeTest,Previous,Where) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",forename,surname,address1,address2,postCode,homePhone,mobilePhone,email,license,expiry,medical,DOB,eyeTest,previous,where)
pyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement. (-3502) (SQLExecDirectW)')
我可能错过了一些简单的事情。
答案 0 :(得分:3)
WHERE
是一个SQL关键字,这使得它作为字段名称的选择很差。如果您无法重命名该字段,请将其用INSERT
语句中的方括号括起来。
... Previous,[Where]) values ...