Procedure documentationExample: Executing SQL Statements and Handling Errors Locate this document in the navigation structure

 

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

Procedure

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

    Syntax Syntax

    1. #
      # Import Python modules
      # ---------------------------------------------------
      import sys
      import sdb.sql
      #
      # Connect to the database
      # ---------------------------------------------------
      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
      # ----------------------------------------------------
      session.release ()
      
    End of the code.
  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