質問

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?

役に立ちましたか?

解決

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)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top