how to catch specific pyodbc error message

前端 未结 5 1094
北恋
北恋 2020-12-18 21:39

I trid the following code,

import pyodbc
try:
    pyodbc.connect(\'DRIVER={%s};SERVER=%s;DATABASE=%s;UID=%s;PWD=%s\' % (driver, server, database, uid, passwo         


        
5条回答
  •  渐次进展
    2020-12-18 22:12

    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.

提交回复
热议问题