Python - SQL 连接器:更新不起作用

Python - SQL Connector: Update do not work

我想更新 MySQL 中的记录。但是,我总是收到语法无效的错误。我认为这是格式错误,但我无法修复它。

错误信息:

mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''ovd' = 1 WHERE id = '16923'' at line 1

我的代码如下:

func = ['OffizierIn vom Dienst Bezirk', 'EinsatzoffizierIn']
dbFields = ["ovd", "offizier"]

x = 0
for i in func:
    el = chrome.find_element_by_id('RoleId')
    for option in el.find_elements_by_tag_name('option'):
        if option.text == i:
            option.click()
    chrome.find_element_by_id('SearchBtn').submit()
    time.sleep(2)
    tbody = chrome.find_element_by_id('SearchResults')
    for row in tbody.find_elements_by_xpath('./tr'):
        itemsEmployee = row.find_elements_by_xpath('./td')
        cursor.execute('UPDATE employees SET %s = 1 WHERE id = %s;', (dbFields[x], itemsEmployee[1].text))
    x = x + 1

在第一遍中,值与错误消息中的值相同:dbFields[x] = ovd itemsEmplyee[1] = 16923

table创建如下:

cursor.execute('CREATE TABLE IF NOT EXISTS employees (id INT NOT NULL UNIQUE, ovd BOOLEAN);')

您在编写动态数据库查询时遇到了一个烦恼:values 必须被引用,如有必要,用引号引起来,如连接器包所执行的那样,但是 table 和列名,如果引用,则用反引号引用。见 MySQL rules.

您需要使用字符串格式添加列名,然后将值传递给准备好的语句:

stmt = f'UPDATE employees SET `{dbFields[x]}` = 1 WHERE id = %s;'
cursor.execute(stmt, (itemsEmployee[1].text,))