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

  • python mysqldb anti sql injection

Using the Python DB API, don’t do this:

Instead, do this:

Note that the placeholder syntax depends on the database you are using.

The values for the most common databases are:

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[, 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:

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.


声明: 除非注明,ixyzero.com文章均为原创,转载请以链接形式标明本文地址,谢谢!



    cmd = "update people set name=%s where id=%s"
    curs.execute(cmd, (name, id))

    # 如果你使用的是 MySQL/PostgreSQL 请一直使用 %s 作为占位符,即便对应的字段是 整型或是其它非字符 类型的值。


    # 不要在占位符那里用 % 拼接,而是在传入的参数那里提前拼接,然后用防注入的方式传入
    c.execute("SELECT * FROM data WHERE params LIKE %s LIMIT 1", ("%" + param + "%",))

a-z进行回复 取消回复

电子邮件地址不会被公开。 必填项已用*标注