Using strings with ' in them in SQL-queries

Michal Wallace (sabren) sabren at manifestation.com
Tue May 30 16:42:17 EDT 2000


On Tue, 30 May 2000 thomas at cintra.no wrote:

> db = _pg.connection(....)
> db.query('insert into test (id, name) value (1, 'fdsfds''fdsf') ')
> 
> That works ok. But the string I need to insert I get from a variable. 
> I cannot seem to use a variable in the query-string. Is there any way
> around this? How can I handle characters in strings that may
> comprimise the requirements of a valid sql-statement??

Hey Thomas,

well, for one thing, you can use double quotes.. :)

   db.query("insert into test (id, name) value (1, 'fdsfds''fdsf') ")

but then, try this:

   import string
   somestring = "a ' value ' with  ' apostrophes"
   somestring = string.replace(somestring, "'", "''")

Cheers,

- Michal
-------------------------------------------------------------------------
http://www.manifestation.com/         http://www.linkwatcher.com/metalog/
-------------------------------------------------------------------------





More information about the Python-list mailing list