views:

119

answers:

3

I'm parsing a xml file and inserting it into database. However since some text containes double or single quotation I'm having problem with insertion. Currently I'm using the code shown below. But it seems it's inefficient.

s = s.replace('"', ' ')
s = s.replace("'", ' ')

Is there any way I can insert text without replacing these quotations?

OR

Is there any efficient way to substitute them efficiently ?

Thanks !

+13  A: 

Why can't you insert strings containing quote marks into your database? Is there some weird data type that permits any character except a quote mark? Or are you building an insert statement with literal strings, rather than binding your strings to query parameters as you should be doing?

If you're doing

cursor.execute('insert into mytable (somefield) values ("%s")' % (mystring))

then that's unsafe and wrong. Instead, you should be doing

cursor.execute('insert into mytable (somefield) values (%(myparam)s)',
                dict(myparam=mystring))
Jonathan Feinberg
+1  A: 

You could try something like _mysql.escape_string():

>>> import _mysql
>>> a = '''I said, "Don't do that"'''
>>> a
'I said, "Don\'t do that"'
>>> _mysql.escape_string(a)
'I said, \\"Don\\\'t do that\\"'

However, the manual recommends using connection.escape_string(), but I think you need a database connection first.

pwdyson
+1  A: 

you should use str.translate instead of doing two replace() calls

>>> import string
>>> quotes_to_spaces=string.maketrans('"\'',"  ")
>>> s=s.translate(quotes_to_spaces)
gnibbler