Python-SQL连接器:更新不起作用 [英] Python - SQL Connector: Update do not work

查看:184
本文介绍了Python-SQL连接器:更新不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要更新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);')

推荐答案

您在编写动态数据库查询时遇到了一个麻烦:必须用引号引起来(如有必要),就像连接器包所执行的那样,但表名和列名如果用引号引起来,则用反号引起来。请参阅MySQL rules

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

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

这篇关于Python-SQL连接器:更新不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆