简体   繁体   English

带有SELECT语句的MySQL ProgrammingError 1064

[英]MySQL ProgrammingError 1064 with SELECT statement

table = "tbl_" + platform + "_chks"
search = "%" + search + "%"

cur.execute('''SELECT check_id,check_name,%s, FROM %s WHERE %s LIKE %s;''', (field,table,field,search))

I'm getting the following error: 我收到以下错误:

ProgrammingError: (1064, "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 ''tbl_linux_chks' WHERE 'check_name' LIKE '%test%'' at line 1) 编程错误:(1064,“你的SQL语法有错误;请查看与你的MySQL服务器版本相对应的手册,以便在'tbl_linux_chks'附近使用正确的语法'在第1行'检查''LIKE'%test%'' )

Try this: 尝试这个:

cur.execute("""SELECT check_id,check_name,{} 
               FROM tbl_{}_chks 
               WHERE {} LIKE '%%{}%%'
               """.format(field,platform,field,search))

The reason this driver developers separate arguments from query is security. 此驱动程序开发人员将参数与查询分开的原因是安全性 So you should take care about the data in the variables before using this solution. 因此,在使用此解决方案之前,您应该注意变量中的数据。

%s query parameter placeholders can only be used for that, query parameters, not for identifiers like table or column names. %s查询参数占位符只能用于查询参数,而不能用于表或列名称等标识符。 When query parameters are used, strings are automatically quoted and escaped before inserted in a query, but quoting for table and column names is different. 使用查询参数时,字符串会在插入查询之前自动引用和转义,但表名和列名的引用不同。

MySQL uses single or double quotes for quoting values, but it uses backticks (`) for quoting identifiers. MySQL使用单引号或双引号来引用值,但它使用反引号(`)来引用标识符。

For this to work correctly, you need to create the query first (using string formatting), then you can execute that query using query parameters: 为了使其正常工作,您需要首先创建查询(使用字符串格式),然后您可以使用查询参数执行该查询:

# `field` and `platform` must not come from user input, or be validated!
table = "tbl_" + platform + "_chks"
query = ('SELECT check_id, check_name, `{0}` FROM `{1}` WHERE `{0}` LIKE %s'
         .format(field, table))
cur.execute(query, ("%" + search + "%",))

Make really sure that platform and fields do not come from user input, otherwise you'll have an sql injection vulnerability. 确保platformfields不是来自用户输入,否则您将有一个SQL注入漏洞。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM