python 防sql注入_Python中的防SQL注入

本文最后更新于2015年6月7日,已超过 1 年没有更新,如果文章内容失效,还请反馈给我,谢谢!

搜索关键字:

python mysqldb anti sql injection

参考链接:

参考解答:

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 ?

==

How do I pass parameters to the cursor.execute method?

Don’t use the ‘%’ concatenation operator, pass them as a series of extra parameters. For instance

>>> cursor.execute("SELECT * FROM my_table WHERE my_column = '%s'" % "column_value")

May do what you want, but more by accident than design. If you change it to;

>>> cursor.execute("SELECT * FROM my_table WHERE my_column = %s", "column_value")

Then the DB-API module will make sure your value is correctly escaped and turned into an object appropriate for the database.

==

execute()函数本身就有接受SQL语句变量的参数位,只要正确的使用(直白一点就是:使用”逗号”,而不是”百分号”)就可以对传入的值进行correctly转义,从而避免SQL注入的发生。

==

execute(sql[, parameters])

Executes an SQL statement. The SQL statement may be parameterized (i. e. placeholders instead of SQL literals). The sqlite3module supports two kinds of placeholders: question marks (qmark style) and named placeholders (named style).

Here’s an example of both styles:

import sqlite3

con = sqlite3.connect(":memory:")

cur = con.cursor()

cur.execute("create table people (name_last, age)")

who = "Yeltsin"

age = 72

# This is the qmark style:

cur.execute("insert into people values (?, ?)", (who, age))

# And this is the named style:

cur.execute("select * from people where name_last=:who and age=:age", {"who": who, "age": age})

print cur.fetchone()

execute() will only execute a single SQL statement. If you try to execute more than one statement with it, it will raise a Warning. Use executescript() if you want to execute multiple SQL statements with one call.

=EOF=

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值