0

I have some code that needs to escape strings to generate a SQL query for MariaDB. I'm using the mysqlclient module. My code uses escape_string to do this. However, in current versions of mysqlclient the escape_string function has been removed. For instance, with mysqlclient 2.1.0 one gets an ImportError on escape_string:

>>> from MySQLdb import escape_string
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name 'escape_string' from 'MySQLdb' (/home/jhaiduce/.local/lib/python3.10/site-packages/MySQLdb/__init__.py)

It seems escape_string was removed deliberately in a pull request that was merged on October 19th this year, see https://github.com/PyMySQL/mysqlclient/pull/511. Not sure why this was done, but I still need to escape a string to construct my query. Can anyone tell me another way to do this?

Shadow
  • 33,525
  • 10
  • 51
  • 64
jhaiduce
  • 408
  • 4
  • 13
  • 2
    Escaping strings to build a sql statement is very dangerous and usually leads to a sql injection attack vector. I'm not sure if that was why escaping was pulled from that library, but that would be my guess. Instead you should be [binding parameters](https://pynative.com/python-mysql-execute-parameterized-query-using-prepared-statement/) to build your sql statement so injection is impossible. – JNevill Dec 14 '21 at 20:49
  • The string escaping occurs in a single function where the string is taken from a configuration file, not from an external source. So accomplishing SQL injection here would be non-trivial. But I see your point, binding parameters would be preferable. – jhaiduce Dec 14 '21 at 20:57
  • 1
    This post has a good description of how to use MySQLdb to run parameterized queries. I agree fully that you should use this method instead of escaping. It takes a short time to get used to this method, but it's safer than escaping, and once you get used to it, I think you'll find it is easier too. https://stackoverflow.com/questions/775296/mysql-parameterized-queries – Bill Karwin Dec 14 '21 at 20:59
  • Thanks, I changed my code to use bind parameters instead. It was trickier than advertised, because documentation for the sqlalchemy.engine.Connection.execute (which I'm using to execute the query) shows '?' in the query in place of the bind parameter, where actually I had to use '%s' to get it to work. Perhaps it's a difference in syntax between mysql and other databases. – jhaiduce Dec 15 '21 at 23:45

0 Answers0