From Python 3.9 i’m trying to do a MySql query like this
select * from brand WHERE text=’L’Orial’.
It works fine from phpMyAdmin but fails from python for all text including quote "’"
brand = "L'Orial"
where = f"text='{brand}'"
brand_pk_id = self.getPrimaryKeyIfExistInTable('brand', where)
def getPrimaryKeyIfExistInTable(self, table, where, key='id'):
try:
sql = f"SELECT {key} FROM {table} WHERE {where}"
self.cursor.execute(sql)
result = self.cursor.fetchone()
return result[key if self.bUseDictCursor else 0] if result else None
except pymysql.MySQLError as e:
logging.error(e)
return None
I can see that python escapes all quotes, which probably causes the problem, but can not figure out how to handle it properly !!
If I turn it around and use query LIKE with underscore( _ ) as wildcard:
brand = "L_Orial"
sql = f"SELECT {key} FROM {table} WHERE text LIKE '{brand}'"
It works fine, but this is not what I want !!
2
Answers
If I am understanding your question correctly, your problem is as follows:
Your query must exactly read:
But you are currently getting something like this, when you use python to execute the query:
If this is indeed the issue, you should be able to resolve this by simply escaping the backslash that you need to have in the query. The complete python string for your query would be:
If you wanted to automatically fix this issue for all brands that might include a
'
, you can simplyreplace
the'
with\'
before making the query. Example:Had to fire up my local instance just to make a point.
First, some prep work…
As somebody suggested in the comments, the following
Raises an error as expected since all the (string) params are quoted, even the table name!
If you can trust the inputs for the table name, the key, and the column name(s) then perhaps a simple query builder can help.
If you need something more elaborate, there are a few modules such as Mysql Simple Query Builder and PyPika – Python Query Builder that you may want to look at (I’ve not used any of these.)