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?
热门推荐
10 喜得孙子祝福语简短唯美
11 婚礼祝福语简短朴实大众
12 员工周年祝福语大全简短
13 家长回复节日祝福语简短
14 简短生日祝福语老同学
15 夜雨祝福语简短10字
16 蛋糕祝福语简短闺蜜
17 部门过年祝福语简短独特
18 简短精炼的结婚祝福语