我知道在使用 python 模块 MySQLdb 的 SELECT 或 INSERT 查询中避免注入(inject)攻击的正确方法是:
cursor.execute("SELECT spam, eggs, sausage FROM breakfast WHERE price < %s", (max_price,))
但是,当我尝试在 CREATE 查询中应用相同的规则时,它返回错误。我的代码:
cursor.execute("CREATE DATABASE %s;", ("test",))
它报告语法错误:
_mysql_exceptions.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 ''test'' at line 1")
似乎是因为查询在数据库名称中添加了单引号,而 Mysql 在 CREATE 查询中不允许这样做?
那么,如果数据库名称或表名称不固定,那么使用 python MySQLdb 模块创建数据库或表的正确方法是什么?
最佳答案
试试方括号;
cursor.execute("CREATE DATABASE %s;", ["test"])
关于python - 如何在python mysql中防止CREATE查询中的注入(inject)攻击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19462050/