Elegent solution to replacing ' and " ?
Serge.Orlov at gmail.com
Sat May 6 05:35:34 CEST 2006
> 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
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:
More information about the Python-list