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?