已关注 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])
关于Pythoncursor.execute() 与 MySQL UPDATE 导致语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54015124/