[Tutor] Building an SQL query
gsf at panix.com
Fri Jun 3 20:07:10 CEST 2005
On Thu, Jun 02, 2005 at 10:41:20PM +0100, Alan G wrote:
> Why not convert the list to a tuple before applying str():
I'm just getting started with Python and PostgreSQL but I found that
str(tuple(valueList)) wouldn't work for me because I had a few values
with apostrophes. PostgreSQL needed 'Lion''s Mane' but Python was
sending it "Lion's Mane", so I ended up writing this little function:
count = 1
y = '('
for x in valueList:
x = x.replace("'", "''")
y = y + "'" + x + "'"
if count < len(valueList):
y = y + ', '
count = count + 1
y = y + ')'
y = y.replace("'NULL'", 'NULL')
Does anyone see any major stumbling blocks in that?
On a side note, I've struggled with PyGreSQL. At first I was using
the pg module, but I switched to pgdb when insert() wasn't working for
me and I thought I would have less trouble using something that's
DB-API compliant. There seemed to be more documentation there, and I
figured it's a good idea to go with the standard. However, it does
seem like I'm covering ground I'm sure someone else has already
crossed when I create these re functions to manipulate queries. For
inserts, at least, it seems a Python dictionary should be able to do
the job nicely.
More information about the Tutor