How to catch a specific pyobbc error message

I skipped the following code,

import pyodbc try: pyodbc.connect('DRIVER={%s};SERVER=%s;DATABASE=%s;UID=%s;PWD=%s' % (driver, server, database, uid, password)) except pyodbc.Error, err: logging.warn(err) 

Error message format i get is

 ('HY000', "[HY000] [MySQL][ODBC 5.1 Driver]Access denied for user 'root'@'192.168.2.27' (using password: YES) (1045) (SQLDriverConnect)") 

I want to receive only a part of the error message i.e.

 Access denied for user 'root'@'192.168.2.27'(using password: YES) 

I do not know if I can catch errors, for example, the driver was not found, the host, etc.

I also tried to catch errors like:

  except pyodbc.OperationalError, err: logging.warn(err) except pyodbc.DataError, err: logging.warn(err) except pyodbc.IntegrityError, err: logging.warn(err) except pyodbc.ProgrammingError, err: logging.warn(err) except pyodbc.NotSupportedError, err: logging.warn(err) except pyodbc.DatabaseError, err: logging.warn(err) except pyodbc.Error, err: logging.warn(err) 

but the latter always detects an error.

Fruthermore, I saw that pyodbc.Error.message is always empty. How can I get only an error message.

thanks

+6
source share
3 answers

pyodbc seems to just wrap errors / exceptions from the underlying ODBC implementation, so it is unlikely that you can do this.

+4
source

It worked for me.

  try: cnxn = pyodbc.connect(...) except pyodbc.Error as ex: sqlstate = ex.args[0] if sqlstate == '28000': print("LDAP Connection failed: check password") 

There are different SQLSTATES, and you can have if-else statements to print the reason.

Similarly

  try: cnxn = pyodbc.connect(...) except pyodbc.Error as ex: sqlstate = ex.args[1] print(sqlstate) 

will give you the second part of the error with the description. For example, ex.args[0] gives you 28000 and ex.args[1] gives [28000] LDAP authentication failed for user 'user' (24) (SQLDriverConnect)

You can then use String manipulation methods to simply print what you want. Hope this helps.

+4
source

In pyodbc 3.0.7, it works fine to catch pyodbc.ProgrammingError (and, presumably, other types of errors, although I have not tried it). The contents of the error are still cryptic, so it may be difficult to perform small-scale error handling.

+2
source

Source: https://habr.com/ru/post/920019/


All Articles