【问题标题】:Passing a column name in an SQL statement in Python?在 Python 的 SQL 语句中传递列名?
【发布时间】:2020-11-04 22:40:43
【问题描述】:

这是我写的代码

def edititem():
    edit_code = int(input("Enter  the product code of the item you would like to edit:"))
    edit_cat =  input("Enter the category of the item you would like to edit:")
    edit_val =  int(input("Enter the new value"))
    edit = """UPDATE products SET %s = %s where prod_code = %s"""
    cur.execute(edit,(edit_cat,edit_val,edit_code,))
    connector.commit()

这是我得到的错误:

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 '' prod_code' = 1 where prod_code = 1231' at line 1

我无法弄清楚究竟是什么错误,这将是一个很大的帮助。在此先感谢。

【问题讨论】:

  • 据我回忆,您不能将对象名称(列名称)传递到 %s 替换逻辑中。格式化程序与值隔离。
  • 那么如何将列名传递给查询?
  • 您可以将语句创建为字符串,并使用字符串格式动态添加表名。请注意可能的注入机会;如果这适用于您的工作环境。
  • @Zeck 问题解决了吗?

标签: python mysql-connector-python


【解决方案1】:

正如@S3DEV 提到的,您不能使用 SQL 参数来插入列名。您必须对这些部分使用经典的字符串格式。

例如,下面是对列使用字符串格式

cursor.execute("SELECT * FROM PacketManager WHERE {} = ?".format(filters[0]), (parameters[0],))

还要注意验证允许的列名的重要性,以确保不会发生注入。

您还应该从此处查看示例 - Use Python list in SQL query for column names

【讨论】:

    猜你喜欢
    • 2021-04-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-06
    • 2023-03-20
    • 2019-06-15
    • 1970-01-01
    • 2021-06-25
    • 2023-03-25
    相关资源
    最近更新 更多