Python光标.执行()与MySQL更新导致语法

2024-03-28 17:07:29 发布

您现在位置:Python中文网/ 问答频道 /正文

this示例之后,我试图重写与防止SQL注入的代码一起工作的代码:

有效代码:

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

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

无效代码:

^{pr2}$

此代码也不起作用:

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

我不知道我做错了什么,所以如果有任何建议,我将不胜感激。在


Tags: 代码testfalse示例fieldexecutesqlled
3条回答

我喜欢在这样的实例中使用psycopg2,在这种情况下,您试图将列名作为输入输入而不希望它转义

from psycopg2.extensions import AsIs

cmd = """
      UPDATE %(table)s SET %(column)s = %(val)s
      """

kwargs = {
    'table': AsIs('led_status'),
    'column': AsIs('test_led'),
    'val': False
}

cursor.execute(cmd, kwargs)

你的SQL在这三个例子中都是不正确的。 以下代码应该有效:

table = "led_status"
field = "test_led"
value = False

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

注意表名和列名周围的反撇号(`),但是,值应该表示为相应对象类型的列。单引号和双引号应该用来表示字符串值。在

在您的例子中,FALSE很可能不是作为字符串存储的,而是作为一个布尔值或tinyint存储在数据库模式中。在

根据文件规定,最佳方法是:

from psycopg2 import sql

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

Source

相关问题 更多 >