欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Pyhton中防止SQL注入的方法

程序员文章站 2023-11-28 19:51:40
复制代码 代码如下: c=db.cursor() max_price=5 c.execute("""select spam, eggs, sausage from b...

复制代码 代码如下:

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 python db api, 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 ?