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正则替换字符串函数re.sub用法示例

Python正则替换字符串函数re.sub用法示例

本文实例讲述了Python正则替换字符串函数re.sub用法。分享给大家供大家参考,具体如下: python re.sub属于python正则的标准库,主要是的功能是用正则匹配要替换的字...

cProfile Python性能分析工具使用详解

cProfile Python性能分析工具使用详解

前言 Python自带了几个性能分析的模块:profile、cProfile和hotshot,使用方法基本都差不多,无非模块是纯Python还是用C写的。本文介绍cProfile。 例子...

利用python批量给云主机配置安全组的方法教程

前言 这几年对运维人员来说最大的变化可能就是公有云的出现了,我相信可能很多小伙伴公司业务就跑在公有云上,  因为公司业务关系,我个人接触公有云非常的早,大概在12年左右就是开始...

PyTorch中topk函数的用法详解

PyTorch中topk函数的用法详解

听名字就知道这个函数是用来求tensor中某个dim的前k大或者前k小的值以及对应的index。 用法 torch.topk(input, k, dim=None, largest=...

tensorboard实现同时显示训练曲线和测试曲线

tensorboard实现同时显示训练曲线和测试曲线

在做网络训练实验时,有时需要同时将训练曲线和测试曲线一起显示,便于观察网络训练效果。经过很多次踩坑后,终于解决了。具体的方法是:设置两个writer,一个用于写训练的数据,一个用于写测试数...