Skip to content
Advertisement

String of cursor.execute without executing

I am using the following approach to using pymysql to parametrize the SQL+args query but not execute it (legitimately, at least):

try:
    self.cursor.execute(self.sql + ' ***', self.sql_args or tuple())    
except pymysql.err.ProgrammingError:                                      
    self._sql_formatted = self.cursor._last_executed.rstrip('* ')

Is there actually a method that pymysql has where it just formats the SQL string without executing it, or do I need to use something like the above? Or, another option:

self.cursor.execute('DESCRIBE ' + self.sql, self.sql_args or tuple())
self._sql_formatted = self.cursor._last_executed.replace('DESCRIBE ', '')

Advertisement

Answer

The cursor.mogrify method

Returns the exact string that is sent to the database by calling the execute() method.

>>> conn = pymysql.connect(host='localhost', user='root', password='password', database='test')
>>> cur = conn.cursor()
>>> stmt1 = """SELECT id, password FROM my_user WHERE name = %s;"""
>>> print(cur.mogrify(stmt1, ('Alice',)))
SELECT id, password FROM my_user WHERE name = 'Alice';
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement