我在views.py中运行了一个动态SQL查询,并且已经运行了其他可以正常工作的查询。我不担心sql注入,因为这是一个私人网站。但是,我的And子句中的参数具有字符“ |”在其中引发错误:
Unknown column "X" in 'where clause'
我已经看过解决方案,但是它们都使用非动态查询,因此禁止我将表名设为变量。
这就是我想要的:
mycursor = mydb.cursor()
assembly_name = "peptides_proteins_000005"
group_id = 5
protein_id = "sp|P48740|MASP1_HUMAN"
qry = "SELECT * FROM %s WHERE group_id = %i AND protein_id = %s" % (assembly_name, group_id, protein_id)
mycursor.execute(qry)
但这会引发错误:
mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column 'sp' in 'where clause'
当我尝试按照类似问题的答案进行操作时,我得到了:
qry = "SELECT * FROM %s WHERE group_id = %i AND protein_id = %s"
mycursor.exectue(qry, (assembly_name, group_id, protein_id))
但是,我仍然收到此错误:
mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement
将%i更改为%s可以修复上面的错误,但随后出现新错误:
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 ''peptides_proteins_000005' WHERE group_id = 5 AND protein_id = 'sp|P48740|MASP1_' at line 1
这是循环结束的地方,因为在线查找此错误建议编写与顶部查询类似的内容。有人可以帮我找出解决方法吗?
答案 0 :(得分:0)
对我来说,这是没有办法的,所以我不得不在%s前后加上文字引号。 我的最终代码如下所示:
assembly_name = peptide_protein_formatter(assembly_name)
mycursor = mydb.cursor()
qry = "SELECT peptide_id,search_id FROM %s WHERE group_id = %s AND protein_id = '%s'" % (assembly_name, group_id, protein_id)
mycursor.execute(qry)
result = mycursor.fetchall()