how to catch specific pyodbc error message how to catch specific pyodbc error message python python

how to catch specific pyodbc error message


This 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 out the cause.

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 description. For exampleex.args[0] give you 28000 and ex.args[1] gives [28000] LDAP authentication failed for user 'user' (24) (SQLDriverConnect)

You can then use String manipulation techniques there to just print out what you want. Hope this helps.


pyodbc seems to just wrap the errors/exceptions from the underlying ODBC implementation, so it's unlikely that you will be able to do this.


In pyodbc 3.0.7, it works fine to catch pyodbc.ProgrammingError (and presumably the other error types, although I haven't tried). The contents of the error are still sort of cryptic, though, so it may be hard to do finer-grained handling of errors.