问题
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