I have a query string that runs in side a loop and for every item in the list query gets executed. The list contains strings and I use python string format technique to replace the query with the respective string from the list as iteration progress.
I have unicoded the query along with the string from the list: Here is my unicoded query:
query = ur'''SELECT something FROM some_table WHERE some_name LIKE "{this_name}%"'''
Prior to execute I encode the query string to utf-8
try:
formatted_query = query.format(this_name=list_name)
#encode the query
encoded_q = formatted_query.encode('utf-8')
# execute the query
self.dbCursor.execute(encoded_q)
row = self.dbCursor.fetchone()
except Exception, e:
traceback.print_exc()
But the problem is that sometimes I run into strings from list that has single quote example: foo's
. I have already unicoded with utf-8 and I thought doing so I don't have to worry about situations like this. But I am getting sql error since MySQL is not skipping the single quote.
My next attempt was to replace the single quote:
format_string = u"foo's".replace(u"'",u"\'")
But this didn't work either. I also saw that answer to this question is using mysqldb library inbuilt functionality which I am not aware of, so I seek the help from stackoverflow community to solve this problem.
I change the code to reflect the solution suggested in answers but result is the same: Here is the change:
args = [u"{this_name}%".format(this_name=format_name)]
self.dbCursor.execute(query.encode('utf-8'), args)
#error get thrown at this line:
Error:
UnicodeEncodeError: 'latin-1' codec can't encode character u'\u014d' in position 4: ordinal not in range(256)
This is the string that error is complaining and I have checked the type of that string its a unicoded string.
this_name= Sentōkisei type= <type 'unicode'>