Pyhton中防止SQL注入的方法
c=db.cursor() max_price=5 c.execute("""SELECTspam,eggs,sausageFROMbreakfast WHEREprice<%s""",(max_price,))
注意,上面的SQL字符串与后面的tuple之间的分隔符是逗号,平时拼写SQL用的是%。
如果按照以下写法,是容易产生SQL注入的:
c.execute("""SELECTspam,eggs,sausageFROMbreakfast WHEREprice<%s"""%(max_price,))
这个和PHP里的PDO是类似的,原理同MySQLPreparedStatements。
Python
UsingthePythonDBAPI,don'tdothis:
#DoNOTdoitthisway.
cmd="updatepeoplesetname='%s'whereid='%s'"%(name,id)curs.execute(cmd)
Instead,dothis:
cmd="updatepeoplesetname=%swhereid=%s"curs.execute(cmd,(name,id))
Notethattheplaceholdersyntaxdependsonthedatabaseyouareusing.
'qmark'Questionmarkstyle,e.g.'...WHEREname=?''numeric'Numeric,positionalstyle,e.g.'...WHEREname=:1''named'Namedstyle,e.g.'...WHEREname=:name''format'ANSICprintfformatcodes,e.g.'...WHEREname=%s''pyformat'Pythonextendedformatcodes,e.g.'...WHEREname=%(name)s'
Thevaluesforthemostcommondatabasesare:
>>>importMySQLdb;printMySQLdb.paramstyleformat>>>importpsycopg2;printpsycopg2.paramstylepyformat>>>importsqlite3;printsqlite3.paramstyleqmark
SoifyouareusingMySQLorPostgreSQL,use%s(evenfornumbersandothernon-stringvalues!)andifyouareusingSQLiteuse?