Pyhton中防止SQL注入的方法

yipeiwu_com6年前Python基础

复制代码 代码如下:

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 ?

相关文章

python字符串的常用操作方法小结

本文实例为大家分享了python字符串的操作方法,供大家参考,具体内容如下 1.去除空格 str.strip():删除字符串两边的指定字符,括号的写入指定字符,默认为空格 >...

使用Python实现BT种子和磁力链接的相互转换

bt种子文件转换为磁力链接 BT种子文件相对磁力链来说存储不方便,而且在网站上存放BT文件容易引起版权纠纷,而磁力链相对来说则风险小一些。而且很多论坛或者网站限制了文件上传的类型,分享一...

django自带serializers序列化返回指定字段的方法

django orm 有个defer方法,指定模型排除的字段。 如下返回的Queryset, 排除‘username', 'id'。 users=models.UserInfo.ob...

计算机二级python学习教程(1) 教大家如何学习python

计算机二级python学习教程(1) 教大家如何学习python

本来PHP还学艺不精,又报了计算机二级Python的考试,还有一个半月的时间,抓紧买了高教社的这两本书,今天正式开始学习这个语言,虽然没法和世界上最好的语言PHP相提并论,但是也值得一学...

pandas的唯一值、值计数以及成员资格的示例

1、Series唯一值判断 s = Series([3,3,1,2,4,3,4,6,5,6]) #判断Series中的值是否重复,False表示重复 print(s.is_un...