methods to prevent SQL injection in Pyhton _python

Source: Internet
Author: User
Tags qmark

Copy Code code as follows:

C=db.cursor ()
Max_price=5
C.execute ("" "SELECT spam, eggs, sausage from breakfast
WHERE Price <%s "" ", (Max_price,))

Note that the delimiter between the above SQL string and the tuple below is a comma, and the usual spelling of SQL is%.

It is easy to generate SQL injection if you follow the following notation:

Copy Code code as follows:

C.execute ("" "SELECT spam, eggs, sausage from breakfast
WHERE Price <%s "" "% (Max_price,))

This and PHP PDO is similar to the principle of MySQL Prepared statements.

Python

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

# do not does it this way.

Copy Code code as follows:

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

Instead, do this:
Copy Code code as follows:

cmd = "Update people set name=%s where id=%s" Curs.execute (cmd, (name, id))

Note This placeholder syntax depends on the database for you are using.
Copy Code code as follows:
' 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:

Copy Code code as follows:

>>> import MySQLdb; Print Mysqldb.paramstyle format >>> import psycopg2; Print Psycopg2.paramstyle pyformat >>> import sqlite3; Print Sqlite3.paramstyle Qmark

So if you are using the MySQL or PostgreSQL, use%s (even to numbers and other non-string values!) and if you are using Sqlit E use?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.