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中split方法用法分析

本文实例讲述了python中split方法用法。分享给大家供大家参考。具体分析如下: split 是非常重要的字符串方法,它是join的逆方法,用来将字符串分割成序列 >>...

python如何实现int函数的方法示例

前言 拖了这么久,最终还是战胜了懒惰,打开电脑写了这篇博客,内容也很简单,python实现字符串转整型的int方法 python已经实现了int方法,我们为什么还要再写一遍,直接用不就好...

Queue 实现生产者消费者模型(实例讲解)

Python中,队列是线程间最常用的交换数据的形式。 Python Queue模块有三种队列及构造函数: 1、Python Queue模块的FIFO队列先进先出。 class Queue...

python实现微信小程序自动回复

本文是使用Python的itchat模块进行微信私聊消息以及群消息的自动回复功能,必须在自己的微信中添加微信号xiaoice-ms(微软的微信机器人)才能实现,直接复制代码运行之后扫一扫...

Python3使用PySynth制作音乐的方法

Python3使用PySynth制作音乐的方法

本人虽然五音不全,但是听歌还是很喜欢的。希望能利用机器自动制作音乐,本我发现了一个比较适合入门的有趣的开源音乐生成模块 PySynth ,文我们主要讲解下如何Python3使用PySyn...