【发布时间】:2020-07-20 21:36:44
【问题描述】:
我正在使用 python3.8 和 mysql.connector。我可以参数化包含LIKE 子句的查询并传入活动的% 通配符吗?
为了驯服我尝试过的传入模式:
pattern = re.sub(r'%+', '%', target)
~and~
pattern = re.sub(r'%+', '%%', target)
~and~
pattern = re.sub(r'%+', '\\%', target)
对于我尝试过的查询:
cursor.execute(f"""
DELETE FROM thnigs
WHERE user = %(user)s
AND widget LIKE %(pattern)s
""", dict(user=username, pattern=pattern))
cursor.execute(f"""
DELETE FROM thnigs
WHERE user = %s
AND widget LIKE %s
""", (username, pattern))
pattern 可以包含任何东西。我知道 mysql.connector 会转义输入,但如果输入字符串包含任意数量的百分比符号,则查询会挂起:1205 (HY000): Lock wait timeout exceeded; try restarting transaction
我尝试将LIKES 切换为RLIKES a 并将通配符更改为简单的.* 字符串,结果相同——如果有任何有效的通配符,则查询终止。
到目前为止还没有起作用的值:
pattern = "%red"
pattern = "red%"
如果这是不可能的,那么我想我可以提取所有值并在应用程序中本地进行通配符搜索,但这感觉不对。可能的数据集可能会变大。
有没有正确或更好的方法?
** 编辑 **
添加了我尝试过的另一个 % 替换模式
【问题讨论】:
标签: python-3.8 mysql-connector-python