problem with quoted strings while inserting into varchar field of database.

Daniele Varrazzo daniele.varrazzo at gmail.com
Sun May 6 14:22:52 EDT 2007


> I further discovered that the string variable that contains the
> pickled object contains a lot of single quots "'" and this is what is
> probably preventing the sql insert from succedding.  can some one
> suggest how to work around this problem?

Every serious database driver has a complete and solid SQL escaping
mechanism. This mechanism tipically involves putting placeholders in
your SQL strings and passing python data in a separate tuple or
dictionary. Kinda

    cur.execute("INSERT INTO datatable (data) VALUES (%s);",
(pickled_data,))

instead of:

    cur.execute("INSERT INTO datatable (data) VALUES ('%s');" %
(pickled_data,))

It is the driver responsibility to serialize the data (which usually
involves adding enclosing quotes and escape odd charaters such as
quotes themselves).

What database/driver are you using? PostgreSQL+psycopg2 or any other
wrong one? ;) In eiither case, read the driver documentation and the
DBAPI documentation (http://www.python.org/dev/peps/pep-0249/) for
further details.

-- Daniele




More information about the Python-list mailing list