很多人在用Python DB API时会用以下方式拼接sql
cmd = "update people set name='%s' where id='%s'" % (name, id) curs.execute(cmd)
然后调用cursor.execute执行,这样容易产生sql注入
正确的方法是使用占位符语法
cmd = "update people set name=%s where id=%s" curs.execute(cmd, (name, id))
execute语句在执行时会先对元组(name, id)的值转为字符串,进行转义,
不同的数据库支持不同占位符语法,常见占位符包括以下:
1.’qmark’ Question mark style, e.g. ‘…WHERE name=?’
2.’numeric’ Numeric, positional style, e.g. ‘…WHERE name=:1′ ‘named’
3.’named’ Named style, e.g. ‘…WHERE name=:name’
4.’format’ ANSI C printf format codes, e.g. ‘…WHERE name=%s’
5.’pyformat’ Python extended format codes, e.g. ‘…WHERE name=%(name)s’
注意pyformat后的s
常见数据库python链接库实现的默认paramstyle
>>>import MySQLdb; print MySQLdb.paramstyle format >>> import psycopg2; >>>print psycopg2.paramstyle pyformat >>> import sqlite3; print sqlite3.paramstyle qmark
如果你在使用MySQL 或 PostgreSQL, 可以用%s
(即使是数字或者非字符)
更全的关于python防止sql注入的资料:下载sqlinjection-120205200846-phpapp01
The post python db api正确使用方式 appeared first on wingyiu.