Error-handling functions in Python

Sometimes errors happen when you attempt to connect to a database or issue an SQL statement. The user name or password might be incorrect, a table or column name might be misspelled, or the SQL statement might be invalid. The ibm_db API provides error-handling functions to help you recover gracefully from the error situations.

Connection errors

Use one of the listed functions to retrieve diagnostic information if a connection attempt fails.

Table 1. ibm_db functions for handling connection errors
Function Description
ibm_db.conn_error Retrieves the SQLSTATE returned by the last connection attempt
ibm_db. conn_errormsg Retrieves a descriptive error message appropriate for an application error log

SQL errors

Use one of the listed functions to retrieve diagnostic information if an attempt to prepare or execute an SQL statement or to fetch a result from a result set fails.

Table 2. ibm_db functions for handling SQL errors
Function Description
ibm_db.stmt_error Retrieves the SQLSTATE returned by the last attempt to prepare or execute an SQL statement or to fetch a result from a result set
ibm_db.stmt_errormsg Retrieves a descriptive error message appropriate for an application error log

For more information about the ibm_db API, see https://github.com/ibmdb/python-ibmdb/wiki/APIs.

Examples

Example 1: Handle connection errors

import ibm_db 
try:
    conn = ibm_db.connect("database","username","password")     
except:     
    print "no connection:", ibm_db.conn_errormsg()
else:
    print "The connection was successful" 

Example 2: Handle SQL errors

import ibm_db
conn = ibm_db.connect("database","username","password")
sql = "DELETE FROM EMPLOYEE"
try:
   stmt = ibm_db.exec_immediate(conn, sql)
except:
   print "Transaction couldn't be completed:" , ibm_db.stmt_errormsg()
else:
   print "Transaction complete."