Edgewall Software

Changes between Version 1 and Version 2 of TracDev/DatabaseApi


Ignore:
Timestamp:
May 27, 2005, 12:52:22 PM (19 years ago)
Author:
Christopher Lenz
Comment:

Comments on string formatting

Legend:

Unmodified
Added
Removed
Modified
  • TracDev/DatabaseApi

    v1 v2  
    1414Code accessing the database in Trac go through this layer simply by using the {{{Environment}}} method {{{get_db_cnx()}}}:
    1515
    16 
    1716{{{
    1817#!python
     
    2322cursor = db.cursor()
    2423# Execute some SQL statements
     24
    2525db.commit()
    2626}}}
     
    5757}}}
    5858
     59At any cost, try avoiding the user of [http://docs.python.org/lib/typesseq-strings.html string formatting] to get values into the SQL statement. The database automatically escapes values you pass using {{{execute()}}} arguments, the same is not true if you use string formatting. If you '''absolutely cannot avoid''' it, be sure to apply the {{{sql_escape}}} function in [source:/trunk/trac/util.py trac.util] to all parameters you're passing in, to avoid possible [http://en.wikipedia.org/wiki/SQL_injection SQL injection] attacks:
     60
     61{{{
     62#!python
     63from trac.util import sql_escape
     64cursor.execute("SELECT author,ipnr,comment FROM wiki WHERE name=%s" % sql_escape(thename))
     65}}}
     66
     67On the other hand, you '''must''' use string formatting to dynamically specify names of tables or columns, i.e. anything that is not a value as such:
     68
     69{{{
     70#!python
     71cursor.execute("SELECT time FROM %s WHERE name=%%s" % table, (thename,))
     72}}}
     73
    5974=== Retrieving results ===
    6075