escape string to store in a database?

andrei.avk at gmail.com andrei.avk at gmail.com
Fri Mar 14 03:55:27 CET 2008


 On Mar 12, 8:32 pm, Carsten Haese <cars... at uniqsys.com> wrote:
> On Wed, 2008-03-12 at 18:18 -0700, andrei.... 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 Haesehttp://informixdb.sourceforge.net

Thanks for the reply, Carsten, how would this work with UPDATE
command? I get this error:

        cmd = "UPDATE items SET content = ? WHERE id=%d" % id

    self.cursor.execute(cmd, content)
pysqlite2.dbapi2.ProgrammingError: Incorrect number of bindings
supplied. The c
rrent statement uses 1, and there are 0 supplied.

Sqlite site doesn't give any details on using parameter bindings in
UPDATE command, I'm
going to look around some more.. -ak



More information about the Python-list mailing list