Methods to prevent SQL injection in Pyhton
- 2020-04-02 14:33:15
- OfStack
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 following tuple is a comma, which is usually spelled with % for SQL.
SQL injection is easy to generate if written as follows:
c.execute("""SELECT spam, eggs, sausage FROM breakfast
WHERE price < %s""" % (max_price,))
This is similar to PDO in PHP, which works like MySQL Prepared Statements.
Python
Using the link: (http://wiki.python.org/moin/DatabaseProgramming/), don 't do this:
Do NOT Do it this way.
cmd = "update people set name='%s' where id='%s'" % (name, id) curs.execute(cmd)
Home, do this:
cmd = "update people set name=%s where id=%s" curs.execute(cmd, (name, id))
Note that the placeholder syntax depends on the database you are using.
'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:
>>> 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 ?