Python3.8, MySQL5.7: passing active wildcards to LIKE query

别等时光非礼了梦想. 提交于 2020-07-22 05:43:09

问题


I am using python3.8 and mysql.connector. Can I parameterize a query that contains a LIKE clause and pass in active % wildcard(s)?

To tame the incoming pattern I have tried:

pattern = re.sub(r'%+', '%', target)
~and~
pattern = re.sub(r'%+', '%%', target)
~and~
pattern = re.sub(r'%+', '\\%', target)

for the queries I have tried:

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 could contain just about anything really. I know that mysql.connector will escape the input but if the input string contains any number of percent symbols the query hangs then dies with: 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

I have tried switching the LIKES for RLIKES aand changing the wildcards to simple .* strings with the same result -- if there is any active wildcard then the query dies.

Values that have not worked so far:

pattern = "%red"
pattern = "red%"

If this is not possible then I suppose I could pull in all values and do the wildcard search locally in the app but that feels wrong. The possible dataset could potentially become large.

Is there a correct or better way?

** Edit ** added another % replacement pattern that i have tried


回答1:


You must escape % with %% in the sql query text that is passed, this is what I remember at least from long ago.

See also

mysql LIKE with double percent

and there my answer.



来源:https://stackoverflow.com/questions/63004189/python3-8-mysql5-7-passing-active-wildcards-to-like-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!