Using strings with ' in them in SQL-queries

D'Arcy J.M. Cain darcy at vex.net
Fri Jun 2 08:22:45 EDT 2000


thomas at cintra.no wrote:
> I need to insert strings with ' in them in query-strings. I`m using
> the PostgreSQL-database. 

> If I try stuff like this :

> db = _pg.connection(....)
> db.query('insert into test (id, name) value (1, 'fdsfds''fdsf') ')

I assume you are using PyGreSQL.  The suggested method to call it is
to use the Python wrapper so...

import pg
db = pg.DB(...)

Now, if you use the insert method instead of a raw query the issue
disappears.

test = db.insert('test', {
    'id': 1,
    'name': "fdsfds'fdsf",
	'active': 'Yes',
	'desc': None,
})

The pg class does the checking and conversion for you.  It even converts
'T', 'TRUE', 'Y', 'YES', 1, '1' and 'ON' (case insensitive) to 't' and
everything else to 'f' if the field is a boolean.  The new version also
turns None into "NULL".

And the return value is the dictionary with the new OID as well as any
changes to the record due to triggers, rules and defaults in the database.

You-learn-about-apostrophes-with-a-name-like-D''Arcy-ly yrs.

-- 
D'Arcy J.M. Cain <darcy at vex.net>           |  Democracy is three wolves
http://www.vex.net/                        |  and a sheep voting on         
+1 416 425 1212     (DoD#0082)    (eNTP)   |  what's for dinner.



More information about the Python-list mailing list