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 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短