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 Excel操作

通过实例学习Python Excel操作

这篇文章主要介绍了通过实例学习Python Excel操作,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.python 读取Exc...

Python Django框架模板渲染功能示例

Python Django框架模板渲染功能示例

本文实例讲述了Python Django框架模板渲染功能。分享给大家供大家参考,具体如下: 项目名/settings.py(项目配置,配置模板文件的路径): import os #...

Tensorflow 同时载入多个模型的实例讲解

有时我们希望在一个python的文件空间同时载入多个模型,例如 我们建立了10个CNN模型,然后我们又写了一个预测类Predict,这个类会从已经保存好的模型restore恢复相应的图结...

TensorFlow 滑动平均的示例代码

滑动平均会为目标变量维护一个影子变量,影子变量不影响原变量的更新维护,但是在测试或者实际预测过程中(非训练时),使用影子变量代替原变量。 1、滑动平均求解对象初始化 ema = tf...

python实现k均值算法示例(k均值聚类算法)

简单实现平面的点K均值分析,使用欧几里得距离,并用pylab展示。 复制代码 代码如下:import pylab as pl #calc Euclid squiredef calc_e_...