Pyhton中防止SQL注入的方法

yipeiwu_com5年前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 basemap 画出经纬度并标定的实例

如下所示: 两个函数:Basemap.drawparallels ##纬度 Basemap.drawmeridians ##经度 from mpl_toolkits.bas...

Python 中字符串拼接的多种方法

python拼接字符串一般有以下几种方法: ①直接通过(+)操作符拼接 s = 'Hello'+' '+'World'+'!' print(s) 输出结果: Hello Worl...

Python中列表的一些基本操作知识汇总

Python中列表的一些基本操作知识汇总

 Python最基本的数据结构是序列(列表/元组)。一个序列中的每个元素都分配有一个数字- 它的位置或索引。第一个索引是0,第二个索引是1,依此类推。 Python有6内置类型...

python的pip安装以及使用教程

python的pip安装以及使用教程

pip的安装,以及使用pip安装包的方法,记录如下,分享给大家: —–安装python的时候勾选了下载pip,不知道为什么没下载。然后就偷懒想着需要哪个包再单独去下载就好了,然后!!!每...

python绘图模块matplotlib示例详解

python绘图模块matplotlib示例详解

前言 Matplotlib 是 Python 的绘图库。作为程序员,经常需要进行绘图,在我自己的工作中,如果需要绘图,一般都是将数据导入到excel中,然后通过excel生成图表,这样操...