Prevention of SQL Injection in Pyhton, and prevention of SQL Injection in pyhton

Source: Internet
Author: User

Prevention of SQL Injection in Pyhton, and prevention of SQL Injection in pyhton

Copy codeThe Code is as follows:
C = db. cursor ()
Max_price = 5
C.exe cute ("SELECT spam, eggs, sausage FROM breakfast
WHERE price <% s ", (max_price ,))

Note that the separator between the preceding SQL string and the subsequent tuple is comma, And the spelling of SQL is %.

If you use the following statements, SQL injection is easily generated:
Copy codeThe Code is as follows:
C.exe cute ("SELECT spam, eggs, sausage FROM breakfast
WHERE price <% s "% (max_price ,))

This is similar to the PDO in PHP and works in the same way as MySQL Prepared Statements.

Python

Using the Python db api, don't do this:

# Do NOT do it this way.
Copy codeThe Code is as follows:
Cmd = "update people set name = '% s' where id =' % S'" % (name, id) curs.exe cute (cmd)

Instead, do this:
Copy codeThe Code is as follows:
Cmd = "update people set name = % s where id = % s" curs.exe cute (cmd, (name, id ))

Note that the placeholder syntax depends on the database you are using.
Copy codeThe Code is 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 codeThe Code is 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 MySQL or PostgreSQL, use % s (even for numbers and other non-string values !) And if you are using SQLite 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.