Executing SQL Statements and Handling Errors

In this example you use the class SQLError of the sdb.sql module. To generate exceptions of this class, you cause the following error situation: You execute a SELECT statement with an incorrect column name and you execute an SQL statement with an incorrect parameter.

Procedure

...

       1.      Create a Python script sample.py with the following contents:

#

# Import Python modules

# ---------------------------------------------------

import sys

import sdb.sql

#

# Connect to the database instance

# ---------------------------------------------------

database_user = sys.argv [1]

database_user_password = sys.argv [2]

database_name = sys.argv [3]

session = sdb.sql.connect (database_user, database_user_password, database_name)

#

# Execute a SELECT statement with an incorrect column

# name unknown (error in the SQL statement)

#----------------------------------------------------

select = "SELECT unknown FROM hotel.customer"

try:

    cursor = session.sql (select)

except sdb.sql.SQLError, err:

    print "ERR [%d] %s" % (err.errorCode, err.message)

    print select

    print ("=" * (err.errorPos - 1)) + '^'

#

# Execute SQL statement with an incorrect parameter

# (error during execution of the SQL statement)

#-----------------------------------------------------

try:

    count = session.sqlX ("""INSERT INTO hotel.customer

    VALUES (?,?,?,?,?,?)""", ['wrong_data_type', 'Mrs', 'Jennifer', 'Parker', '10590', '0 N.Ash Street, #6'])

except sdb.sql.SQLError, err:

    print "ERR [%d] %s" % (err.errorCode, err.message)

#

# Close connection to the database instance

# ----------------------------------------------------

session.release ()

       2.      Call the Python script:

python sample_6.py MONA RED DEMODB

ERR [-4005] Unknown column name:UNKNOWN

SELECT unknown FROM hotel.customer

=======^

ERR [-817] Incompatible data types

See also:

Examples for the sdb.sql Module