Python操作MySQL时防止SQL注入

2014-11-24 18:29:25 · 作者: · 浏览: 1

下面是网上搜到的一篇关于SQL注入的文章。最近在项目中涉及到防止SQL注入的部分,但是由于使用的是PYTHON和MYSQL,使用不了JAVA代码中提供的一些现成的方法,而且MYSQLDB模块中的EXECUTE方法不支持表名使用占位符。




Execute a query.


query -- string, query to execute on serverargs -- optional sequence or mapping, parameters to use with query.


Note: If args is a sequence, then %s must be used as theparameter placeholder in the query. If a mapping is used,%(key)s must be used as the placeholder.


Returns long integer rows affected, if any


Placeholders are supposed to be used for *values*, not other parts of the SQL statement. To insert table names, column names and stuff like that, use Python-level formatting.


cur.execute("select * from %s where name=%s",('t1','xx')) --python-level formatting,执行失败


cur.execute("select * from %s where name=%s"%('t1','xx')) --execute()-level formatting,执行成功,但是并没有达到防止SQL注入的效果


下面是文档上的一个例子



To perform a query, you first need a cursor, and then you can executequeries on it:



In this example, max_price=5 Why, then, use%s in thestring Because MySQLdb will convert it to a SQL literal value, whichis the string '5'. When it's finished, the query will actually say,"...WHERE price < 5".


无奈之下手工实现,需要两步:


1、把变量值中的单引号逃逸掉


2、给变量值两端加上单引号