How do I escape SQL values when using the DB-API?
You don’t. Instead of constructing SQL statements yourself, use parameter markers, and pass the data to execute in a separate tuple:
db = dbapi.connect(args)
c = db.cursor()
c.execute(
"SELECT * FROM TABLE WHERE NAME=? AND ADDRESS=?",
(name, address)
)
for row in c.fetchall():
print rowThe database driver will either escape the values for you, or, better, pass the values to the database via a separate API. This often gives you better performance, and more importantly, eliminates common forms of SQL injection attacks.
The exact syntax to use for parameters depends on what database you are using; for example, sqlite3 uses “?” markers, while MySQLdb usually uses “%s” markers. You can use the paramstyle variable to check what syntax your database expects.
CATEGORY: database
CATEGORY: programming
Comment:
Additionally, it might be worth mentioning that the parmeter passing is for literal values only - you can't use it to pass a column name.
Posted by Diez B. Roggisch (2007-01-02)

Comment:
Perhaps we should include something which says that you can generally only perform substitutions in the WHERE clause of a SELECT statement, the UPDATE and WHERE clauses of an UPDATE statement or the VALUES clause of an INSERT statement.
There have been occasions on the db-sig mailing list where people have put placeholders in the FROM or SELECT clauses and then not got the results they expected - usually this returns a syntax exception.
Posted by Andy Todd (2006-11-28)