Elegent solution to replacing ' and " ?

F

fyleow

I'm trying to replace the ' and " characters in the strings I get from
feedparser so I can enter it in the database without getting errors.
Here's what I have right now.

self.title = entry.title.encode('utf-8')
self.title = self.title.replace('\"', '\\\"')
self.title = self.title.replace('\'', '\\\'')

This works just great but is there a more elegent way to do this? It
looks like maybe I could use the translate method but I'm not sure.
 
J

Jim

Are you sure that your dB interface module doesn't do this for you?
What dB and interface are you using?

Jim
 
S

Serge Orlov

fyleow said:
I'm trying to replace the ' and " characters in the strings I get from
feedparser so I can enter it in the database without getting errors.
Here's what I have right now.

self.title = entry.title.encode('utf-8')
self.title = self.title.replace('\"', '\\\"')
self.title = self.title.replace('\'', '\\\'')

This works just great but is there a more elegent way to do this? It
looks like maybe I could use the translate method but I'm not sure.

You should use execute method to construct sql statements. This is
wrong:

self.title = entry.title.encode('utf-8')
self.title = self.title.replace('\"', '\\\"')
self.title = self.title.replace('\'', '\\\'')
cursor.execute('select foo from bar where baz="%s" ' % self.title)

This is right:

self.title = entry.title
cursor.execute("select foo from bar where baz=%s", (self.title,))

The formatting style differs between db modules, take a look at
paramstyle description in PEP 249:
http://www.python.org/dev/peps/pep-0249/
 
F

fyleow

I'm using PyGreSQL on a PostgreSQL db.

I didn't even include my SQL but Serge guessed right and that's what I
had. I changed it and it works now.

Thanks for the help! :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top