This example describes the following steps:
...
1. How to create a database session
2. How to log on to a database instance
3. How to query whether a table exists
4. How to create a table or query an error code
5. How to log off
# To reference Python libraries:
# ----------------------------
import sys
import sapdb.loader
# To create a Loader session: (the most recent version of
# Loader is started; there is still no connection
# to the
database instance)
# ------------------------------------------------------
session = sapdb.loader.Loader ()
# To log on to the database:
# To make the example easier to follow, the logon process has been
# shortened here; the parsing of call arguments has
# also been omitted.
# -------------------------------------
session.cmd ('use user %s %s serverdb %s' % tuple (sys.argv [1:4]))
# To query whether a table exists:
# The SQL method is used here;
# if the table does not yet exist, Loader
# returns an error; and the table is
# created
# -------------------------------------
sqlrc = session.sql("EXISTS TABLE CUSTOMER")
if (sqlrc == 0):
print 'Table CUSTOMER exists'
elif (sqlrc == -4004):
# To create the CUSTOMER table:
# -------------------------------------
session.sql("""
CREATE TABLE customer
(
cno FIXED(4,0) PRIMARY KEY,
title CHAR(7),
firstname CHAR(10),
name CHAR(10) NOT NULL,
zip CHAR(5),
address CHAR(25) NOT NULL,
CONSTRAINT cno_cons CHECK cno > 0,
CONSTRAINT title_cons CHECK title IN
('Mr','Mrs','Company'),
CONSTRAINT zip_cons CHECK
SUBSTR(ZIP,1,1) BETWEEN '1' AND '9' AND
SUBSTR(ZIP,2,1) BETWEEN '0' AND '9' AND
SUBSTR(ZIP,3,1) BETWEEN '0' AND '9' AND
SUBSTR(ZIP,4,1) BETWEEN '0' AND '9' AND
SUBSTR(ZIP,5,1) BETWEEN '0' AND '9'
)""")
print 'Table CUSTOMER created'
session.cmd ("COMMIT")
# To end the database session:
# -------------------------------------
del session