panofish
panofish

Reputation: 7889

Python mysql string substitution not working

I've been using this syntax with great success in python mysql.

search = "O'%"   # find names like O'Brien or O'Connell...

cursor.execute ("""
   select userid
      from usertab
    where name like %s
""" , (search))

But sometimes I need to build my sql string before I execute it like the following, but the substitution technique is different than above and doesn't work in all cases.

search = "O'%"   # find names like O'Brien or O'Connell...

sql = """
   select userid
      from usertab
    where name like '%s'
""" % (search)

cursor.execute(sql)

How can I achieve the same kind of string substitution that works well in the first example, without executing the cursor?

Upvotes: 1

Views: 927

Answers (1)

mata
mata

Reputation: 69032

MySQLdb uses the connection's literal() method to escape the arguments, so you could use:

sql = """
   select userid
      from usertab
    where name like %s
""" % cursor.connection.literal(search)

Upvotes: 2

Related Questions