栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Pyhton中防止SQL注入的方法

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Pyhton中防止SQL注入的方法

复制代码 代码如下:
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 ?

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/35699.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号