简体   繁体   中英

PYODBC error 07002 - Too few parameters

Put simply, this code takes a quantity of a stock item,and updates the value by adding a number from one of the GUI elements. Whenever I try to run the code below:

Change = self.ui.Modify_Stock_Screen_Change.text()
Change = int(Change)
DBConnect = pyodbc.connect('Driver={Microsoft Access Driver (*.mdb, *.accdb)}; Dbq=H:\\Computer Science\\X\\Y\\Z\\Database.accdb;')
DBSelect = DBConnect.cursor()
DBSelect.execute("select * from Stock where Stock_Item = ?", self.ui.Modify_Stock_Screen_Item.currentText())
TableRow= DBSelect.fetchone()
for Field in TableRow:
    CurrentQuantity = TableRow[1]
    CurrentQuantity = int(CurrentQuantity)
    UpdatedQuantity = int(CurrentQuantity + Change)
    DBSelect.execute('update Stock set Current_Quantity = UpdatedQuantity where Stock_Item = ?', self.ui.Modify_Stock_Screen_Item.currentText())
    DBConnect.commit()

I get the following error:

DBSelect.execute('update Stock set Current_Quantity = "UpdatedQuantity" where Stock_Item = ?', self.ui.Modify_Stock_Screen_Item.currentText())
pyodbc.Error: ('07002', '[07002] [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 2. (-3010) (SQLExecDirectW)')

The problem here is that the Python variable name UpdatedQuantity was included in the SQL command text but the database engine has no idea that such a Python variable exists or what its value might be. That variable needs to be included in the parameters that are passed to the query:

sql = 'update Stock set Current_Quantity = ? where Stock_Item = ?'
params = (
    UpdatedQuantity, 
    self.ui.Modify_Stock_Screen_Item.currentText()
    )
DBSelect.execute(sql, params)

Problem is about quotes. Like in example below:

Good version:

curs.execute(f"select name, surname from employee where occupation='{param}'")

Bad version:

curs.execute(f"select name, surname from employee where occupation={param}")

Select or update, it doesn't matter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM