escape string to store in a database?

Carsten Haese carsten at uniqsys.com
Wed Mar 12 21:32:24 EDT 2008


On Wed, 2008-03-12 at 18:18 -0700, andrei.avk at gmail.com wrote:
> These pieces of text may have single and double quotes in
> them, I tried escaping them using re module and string module and
> either I did something wrong, or they escape either single quotes or
> double quotes, not both of these. So that when I insert that text into
> a db record, this causes an error from the database. What's the
> accepted way of dealing with this?

The accepted way of dealing with this is to use parameter binding:

conn = somedbmodule.connect(...)
cur = conn.cursor()
cur.execute("insert into sometable(textcolumn) values (?)", 
            (stringvar,) )

(Note that the question mark may have to be replaced with %s depending
on which database module you're using.)

For background information on parameter binding see, for example,
http://informixdb.blogspot.com/2007/07/filling-in-blanks.html .

HTH,

-- 
Carsten Haese
http://informixdb.sourceforge.net





More information about the Python-list mailing list