メモ。
Python の MySQLdb で like 検索を行う場合。
import MySQLdb connector = MySQLdb.connect( host=host, port=port, db=db, user=user, passwd=password, use_unicode=0, charset='utf8' ) cursor = connector.cursor() param = 'python' sql = """SELECT * FROM news where title lilke '%%s%'""" sql = sql % param cursor.execute(sql); rows = cursor.fetchall()
とかやると、エラーになった。
ValueError: unsupported format character ''' (0x27)
sql = """SELECT * FROM news where title lilke '%s'""" sql = sql % ('%%%s%%' % param)
とやると、意図通り動いた。
2011/11/13 追記:
cursor.execute("""SELECT * FROM news WHERE title LIKE %s""", ("%python%",))
というように第二引数に設定するといけるとコメントで教えて頂きました。
ありがとうございます!