Question

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?

Was it helpful?

Solution

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top