This is an old copy of the Python FAQ. The information here may be outdated.

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()

    (name, address)
for row in c.fetchall():
    print row

The 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


A Django site. rendered by a django application. hosted by webfaction.