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