Search code examples
pythonmysqlunicodesql-like

Python mysql connector LIKE against unicode value


So here is my problem: I am trying to select a specific value from a table comparing it with a unicode string. The value is also unicode. I am using mysql.connector. The server settings are all utf8 oriented. When I run following query - I get an empty list. When I run it without 'WHERE Title like '%s'' part, I get a full set of values, and they properly displayed in the output. The same query works in the command line on the server. The value is there for sure. What is it that I am missing?

conn = sql.connect(host='xxxxxxx', user='xxx', password='xxx', database='db', charset="utf8")

cur = conn.cursor()

townQuery = (u"""SELECT * FROM Towns  WHERE Title like '%s' """)
tqd = (u"%" +u"Серов"+u"%")
cur.execute(townQuery, tqd)

for  i in cur:
    print i

Solution

    • When you use the 2-argument form of cur.execute (thus passing the arguments, tqd, to the parametrized sql, townQuery), the DB adaptor will quote the arguments for you. Therefore, remove the single quotes from around the %s in townQuery:

      townQuery = u"""SELECT * FROM Towns  WHERE Title like %s"""
      tqd = [u"%Серов%"]
      cur.execute(townQuery, tqd)
      
    • Also note that the second argument, tqd, must be a sequence such as a list or tuple. The square brackets around u"%Серов%" makes [u"%Серов%"] a list. Parentheses around u"%Серов%" do NOT make (u"%Серов%") a tuple because Python evaluates the quantity in parentheses to a unicode. To make it a tuple, add a comma before the closing parenthesis: (u"%Серов%",).