【问题标题】:Python - SQL Connector: Update do not workPython - SQL 连接器:更新不起作用
【发布时间】:2021-07-25 21:20:52
【问题描述】:

我想更新 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] = ovditemsEmplyee[1] = 16923

表的创建如下:

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

【问题讨论】:

    标签: python mysql python-3.x mysql-python


    【解决方案1】:

    您在编写动态数据库查询时遇到了烦恼之一:values 必须在必要时用引号括起来,这由连接器包执行,但 table 和 column名称,如果引用,则用反引号引用。请参阅MySQL rules

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

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

    【讨论】:

      猜你喜欢
      • 2021-03-31
      • 2016-07-05
      • 1970-01-01
      • 2013-04-03
      • 2019-10-10
      • 1970-01-01
      • 1970-01-01
      • 2019-03-18
      • 2015-09-30
      相关资源
      最近更新 更多