Entering content frame

This graphic is explained in the accompanying text Handling Error Situations Locate the document in the library structure

If an error occurs when executing an SQL statement, an exception of the SQLError class is generated.

 

1. Creating the Python file sample_6.py:

#

# To reference Python libraries:

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

import sys

import sdb.sql

#

# Starting the session with 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)

#

# Creating a PYTEST test table;

# to ensure that it is not already available,

# a statement is then executed to delete

# the table

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

try:

    session.sql ("DROP TABLE PYTEST")

except sdb.sql.SQLError:

    pass

session.sql ("""CREATE TABLE PYTEST (

    keycol VARCHAR (20),

    datacol VARCHAR (100),

    PRIMARY KEY (keycol),

    CHECK datacol <> 'invalid' )

    """)

session.sql ("INSERT INTO PYTEST VALUES ('a', 'aval')")

#

# To display errors in SQL statements:

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

select = "SELECT unknown FROM PYTEST"

try:

    cursor = session.sql (select)

except sdb.sql.SQLError, err:

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

    print select

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

#

# To display errors during execution:

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

try:

    count = session.sqlX ("""

        INSERT INTO PYTEST (keycol, datacol)

        values (?, ?)""", ['b', 'invalid'])

except sdb.sql.SQLError, err:

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

#

# Ending the session with the database instance

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

session.release ()

 

2. To call the Python file sample_6.py from the command line and transfer database user MONA’s data to the Python program with the password RED and the database instance named DEMODB, specify the following:

python sample_6.py MONA RED DEMODB

 

 

Leaving content frame