当前位置: 移动技术网 > IT编程>脚本编程>Python > Pyhton中防止SQL注入的方法

Pyhton中防止SQL注入的方法

2019年03月23日  | 移动技术网IT编程  | 我要评论

虹影,夏至习俗,逐梦郁金香

复制代码 代码如下:

c=db.cursor()
max_price=5
c.execute("""select spam, eggs, sausage from breakfast
          where price < %s""", (max_price,))

注意,上面的sql字符串与后面的tuple之间的分隔符是逗号,平时拼写sql用的是%。

如果按照以下写法,是容易产生sql注入的:

复制代码 代码如下:

c.execute("""select spam, eggs, sausage from breakfast
          where price < %s""" % (max_price,))

这个和php里的pdo是类似的,原理同mysql prepared statements。

python

using the , don't do this:

# do not do it this way.

复制代码 代码如下:

cmd = "update people set name='%s' where id='%s'" % (name, id) curs.execute(cmd)

instead, do this:
复制代码 代码如下:

cmd = "update people set name=%s where id=%s" curs.execute(cmd, (name, id))

note that the placeholder syntax depends on the database you are using.
复制代码 代码如下:
'qmark' question mark style, e.g. '...where name=?' 'numeric' numeric, positional style, e.g. '...where name=:1' 'named' named style, e.g. '...where name=:name' 'format' ansi c printf format codes, e.g. '...where name=%s' 'pyformat' python extended format codes, e.g. '...where name=%(name)s'

the values for the most common databases are:

复制代码 代码如下:

>>> import mysqldb; print mysqldb.paramstyle format >>> import psycopg2; print psycopg2.paramstyle pyformat >>> import sqlite3; print sqlite3.paramstyle qmark

so if you are using mysql or postgresql, use %s (even for numbers and other non-string values!) and if you are using sqlite use ?

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网