Search code examples
pythonmysqlpymysql

Extracting text from mysql server error []


If I issue an invalid sql statement in pymysql I get an exception as follows:

c.cursor.execute('select * fromd')
pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'fromd' at line 1")

How would I get the textual error in the response?

"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'fromd' at line 1"

Currently what I'm doing is:

try:
    c.cursor.execute('asdf')
except Exception as e:
    print (e)

But this gives me a "string tuple". Is there a way in this module to just get the error message itself?


Solution

  • You can use e.args:

    try:
        self.cursor.execute(query)
    except pymysql.err.ProgrammingError as e:
        error_msg = e.args[1]
        raise ConnectionError(error_msg)
    

    You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'asdf' at line 1