Pythoncursor.execute() 与 MySQL UPDATE 导致语法错误

标签 python mysql sql-injection

已关注 this例如,我正在尝试重写与防止 SQL 注入(inject)的代码一起使用的代码:

有效的代码:

table = "led_status"
field = "test_led"
value = "FALSE"

cursor.execute(("UPDATE %s SET %s = %s") % (table, field, value))

无效的代码:

table = "led_status"
field = "test_led"
value = "FALSE"

cursor.execute(("UPDATE %s SET %s = %s", table, field, value))

此代码也不起作用:

table = "led_status"
field = "test_led"
value = "FALSE"

sql_update_command = "UPDATE %s SET %s = %s"
cursor.execute(sql_update_command, (table, field, value))

第一个示例有效,其他示例无效,并且每个示例都会抛出此语法错误:

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 ''led_status' SET 'test_led' = 'FALSE'' at line 1

我不确定我做错了什么,所以任何指示将不胜感激。

最佳答案

根据文档执行此操作的最佳方法是:

from psycopg2 import sql

cur.execute(
sql.SQL("insert into {} values (%s, %s)")
    .format(sql.Identifier('my_table')),
[10, 20])

Source

关于Pythoncursor.execute() 与 MySQL UPDATE 导致语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54015124/

相关文章:

python - Django 导入-导出 : IntegrittyError when trying to insert duplicate record in field(s) with unique or unique_together constraints

mysql - 如何在magento中测试sql查询?

mysql - 在 mysql 服务器上触发两个查询会出现错误

sql-injection - 避免 Azure DocumentDB 存储过程中的 SQL 注入(inject)

c# - 当它作为字符串出现时,保护完整的 where 语句

python - TensorFlow Keras CuDNNGRU 到 GRU 转换

python - 用 numpy tensordot 进行张量乘法

python - 我对 Project Euler 71 的逻辑有什么问题?

mysql - 无法从另一个存储例程中创建 TRIGGER - 另一个 "stored routine"是什么?

php - 如何防止 PHP 中的 SQL 注入(inject)?