[英]MYSQL parameter python issue with table name
我是使用 python API 向 mysql 发送查询的新手。
我的问题很容易重现。 我有一个名为“ingredient”的表,我想使用参数 select python 中的行
If I do cursor.execute("select * from?",('ingredient',))
I get the error message: Error while connecting to MySQL Not all parameters were used in the SQL statement MySQL connection is closed
II 执行cursor.execute("select * from?",'ingredient')
我收到错误消息: Error while connecting to MySQL 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 '?' at line 1
Error while connecting to MySQL 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 '?' at line 1
使用 %s 而不是? 在 'ingredient' 上使用其他类型的单引号而不是 'ingredient' 也不会产生结果。
这应该如何在这里工作?
您只是不能将表名作为参数传递给查询。 参数化机制用于传递文字值,而不是 object 名称。 请记住,数据库必须能够仅从参数化字符串(没有实际参数值)准备查询计划,这不符合使用元数据作为参数的资格。
您需要字符串连接:
cursor.execute("select * from " + yourvar);
请注意,如果变量来自您的程序外部,则使用此类结构会将您的代码暴露给 SQL 注入。 您需要在执行查询之前手动验证参数的值(例如,根据允许值的固定列表检查它,或者通过查询数据库的信息模式以确保表确实存在)。
如果您只写以下内容,您的查询是否有效:
cursor.execute("SELECT * FROM ingredient")
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.