[mod_python] Re: error while inserting data

Jorey Bump list at joreybump.com
Mon Jan 9 11:28:25 EST 2006

Daniel Nogradi wrote:
> Inserting variables of type string into other strings goes like this:
> name = "John"
> formatted_string = "your name is: %s" % name
> or with more variables:
> name = "John"
> age = "13"
> formatted_string = "your name is: %s and your age is: %s" % ( name, age )
> Thus you should have:
> (firstname,middlename,lastname) VALUES (%s, %s, %s)" %
> (fname,mname,lname) )
> Note the % sign.

As a safeguard against SQL injection, data should always be inserted 
into a database using placeholders, especially if supplied by users (or 
any external interface, no matter how authoritative). This is typically 
in the form cursor.execute(querystring, tuple):

querystring = "INSERT INTO user (fname, lname) VALUES (%s, %s)"
values = (firstname, lastname)
cursor.execute(querystring, values)

Using simple python string substitution is quite dangerous in web forms. 
Placeholders allow the database to do the work of escaping values safely.

More information about the Mod_python mailing list