【发布时间】:2019-06-27 21:46:29
【问题描述】:
我正在 django 中创建一个网站,我希望用户在其中输入表 id 和组 id,然后返回放入的表和组。但是,我只找到了容易发生 SQL 注入的语句。有人知道如何解决这个问题吗?
mycursor = mydb.cursor()
qry = "SELECT * from %s WHERE group_id = %i;" % (assembly_name, group_id)
mycursor.execute(qry)
return mycursor.fetchall()
或者做一些达到同样目的的事情?
我尝试过这样做:
assembly_id = 'peptides_proteins_000005'
group_id = 5
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM %s WHERE group_id = %s", [assembly_id, group_id])
myresult = mycursor.fetchall()
但我收到此错误:
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' at line 1
【问题讨论】:
-
你可以尝试使用 Django ORM,它可以防止这些安全风险。
-
您将参数作为列表或元组添加为
execute调用的第二个参数,而不是使用%格式。 -
cursor.execute的第二个参数用于参数,如the documentation 所示 -
@KlausD。当您在表格点中有变量时,这不起作用
-
@CraigMeier 见上文
标签: python sql django sql-injection django-2.2