Python 格式化sql%like%
我正在尝试执行以下查询:Python 格式化sql%like%,python,mysql,Python,Mysql,我正在尝试执行以下查询: select count(*) from video where territories like %ZW% 以下是我目前拥有的,但它引发了一个错误: for territory_code in ALL_TERRITORIES: sql = "select count(*) from video where territories like %{}%".format(territory_code) cursor.execute(sql) 这里我做错了
select count(*) from video where territories like %ZW%
以下是我目前拥有的,但它引发了一个错误:
for territory_code in ALL_TERRITORIES:
sql = "select count(*) from video where territories like %{}%".format(territory_code)
cursor.execute(sql)
这里我做错了什么,我该如何正确地缩放%%?如果你这样做,你需要一个带单引号的文本字符串
select count(*) from video where territories like '%ZW%'
也许你可以在下面这样的句子后面用简单的引号:
"select count(*) from video where territories like '%{}%'"
%%周围缺少“”个单引号。改用这个:
"select count(*) from video where territories like '%{}%'"
更好的方法是:
sql = "select count(*) from video where territories like %s"
cursor.execute(sql, ('%' + territory + '%',))
使用这种方法,您将能够参数化查询,而不必担心转义,更重要的是,不必担心转义