如何使用 LIKE 子句转义 pymysql 中的 % 和 \ 符号?
How to escape the % and \ signs in pymysql using LIKE clause?
我想在我的 'events' 列中找到类似 "probability: 10%" 或“10% 高”的内容,但是当我使用以下代码时:
conn = pymysql.connect(host="localhost", port=3306, user='myid', passwd='mypwd', db='mydb', charset='utf8')
curs = conn.cursor()
key = "%"
curs.execute(
"SELECT count(*) AS number FROM city WHERE events LIKE %s",
("%" + key + "%",)
)
它返回了 table 中的每一行。它执行了这个查询:
SELECT count(*) AS number FROM city WHERE events LIKE '%%%'
像这样,我不是故意的。
搜索反斜杠符号也给了我错误的结果。
我应该怎么做才能得到正确的结果?
提前致谢。
您应该使用 SQL ESCAPE 子句:
curs.execute(
"SELECT count(*) AS number FROM city WHERE events LIKE '%#%%' ESCAPE '#'"
)
您可以在 SQL 中使用 concat 并传递值
而不是 concat 参数中的通配符
curs.execute(
"SELECT count(*) AS number FROM city WHERE events LIKE CONCAT('%', %s, '%')",
(key ,)
)
或@Notinlist
所建议的
curs.execute(
“SELECT count(*) AS number FROM city WHERE events LIKE CONCAT('%%', %s, '%%')”,
(钥匙 ,)
)
我想在我的 'events' 列中找到类似 "probability: 10%" 或“10% 高”的内容,但是当我使用以下代码时:
conn = pymysql.connect(host="localhost", port=3306, user='myid', passwd='mypwd', db='mydb', charset='utf8')
curs = conn.cursor()
key = "%"
curs.execute(
"SELECT count(*) AS number FROM city WHERE events LIKE %s",
("%" + key + "%",)
)
它返回了 table 中的每一行。它执行了这个查询:
SELECT count(*) AS number FROM city WHERE events LIKE '%%%'
像这样,我不是故意的。
搜索反斜杠符号也给了我错误的结果。
我应该怎么做才能得到正确的结果?
提前致谢。
您应该使用 SQL ESCAPE 子句:
curs.execute(
"SELECT count(*) AS number FROM city WHERE events LIKE '%#%%' ESCAPE '#'"
)
您可以在 SQL 中使用 concat 并传递值
而不是 concat 参数中的通配符 curs.execute(
"SELECT count(*) AS number FROM city WHERE events LIKE CONCAT('%', %s, '%')",
(key ,)
)
或@Notinlist
所建议的curs.execute( “SELECT count(*) AS number FROM city WHERE events LIKE CONCAT('%%', %s, '%%')”, (钥匙 ,) )