Python: ValueError: unsupported format character ''' (0x27) at index 1

今天写python程序,用pymysql从数据库查询数据,使用like模糊匹配报错:

query_string = "SELECT DATE_FORMAT(movie.publish_time,'%Y-%m-%d'),movie.movie_name FROM movie WHERE movie.publish_time > now() and movie.media_type = 'movie' and movie.movie_type like '%%%%%s%%%%';"
query_param = ["喜剧"]

执行

count = cur.execute(query_string, query_param)

报错

Python: ValueError: unsupported format character ''' (0x27) at index 1

解决方案:
1)

query_param = ['%%%s%%' % '喜剧']
query_string = "SELECT left(movie.publish_time,10),movie.movie_name FROM movie WHERE movie.publish_time > now() and movie.media_type = 'movie' and movie.movie_type like %s;"

count = cur.execute(query_string, query_param)

2)

query_param = ['喜剧']
query_string = "SELECT left(movie.publish_time,10),movie.movie_name FROM movie WHERE movie.publish_time > now() and movie.media_type = 'movie' and movie.movie_type like '%%%s%%';"

count = cur.execute(query_string % tuple(query_param))

解释:
1)MySQL DB使用%运算符将参数放入查询中,因此查询字符串中的任何单个%字符都被解释为参数说明符的开始。
2)%在python中三个特殊的符号,如%s,%d分别代表了字符串占位符和数字占位符。

猜你喜欢

转载自blog.csdn.net/qq_35790269/article/details/81912953
今日推荐