1

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?

0

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

5 Comments

that works... I want to sit on this for day to see what others might suggest... I'm curious how others approach the same problem.
this solution becomes cumbersome when you have several substitutions.
what do you mean with several substitutions? you can just pass a tuple, and each element will be escaped individually: "select ... where a = %s and b = %s and ..." % literal((a, b, ...))
ooo.... interesting. How can I use the short name literal as in your example instead of cursor.connection.literal ?
I just forgot to add that part, but you could just use literal = cursor.connection.literal to make it available as literal if that makes it easier (or connection.literal, no real need to get it from cursor...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.