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?