To create a connection, copy the corresponding arguments from the following examples to the command line.
Use the following command to call the sample.py Python script and log on to the HOTELDB database instance with DBM as the user name and password.
python sample.py DBM DBM HOTELDB
# To reference Python libraries:
# --------------------------------
import sys
import sapdb.sql
# To parse call arguments:
# --------------------------
user_name = sys.argv [1]
password = sys.argv [2]
database_name = sys.argv [3]
# To create a Database Manager session:
# ------------------------------------------------------
session = sapdb.sql.connect (user_name, password, database_name)
# To log off:
# -------------------------------------
session.release ()
The following examples specify a shortened login process:
user_name, password, database_name = sys.argv [1:4]
session = sapdb.dbm.DBM (name, password, database_name)
A SELECT statement returns an object of the SapDB_ResultSet class. This object allows you to call each result row in sequence, without loading the entire result set in the main memory.
# To reference Python libraries:
# --------------------------------
import sys
import sapdb.sql
# To create an SQL session:
# ------------------------------------------------------
user_name, password, database_name = sys.argv [1:4]
session = sapdb.sql.connect (user_name, password, database_name)
select = """
SELECT msgno, language, msgtext FROM messages
WHERE msgno BETWEEN -1000 AND -1"""
# If the SQL method executes a SELECT statement,
# the result is an object of the SAPDB_ResultSet class.
cursor = session.sql (select)
# The next method returns the following row of the result set.
row = cursor.next ()
while row:
errorcode, language, message = row
print "%6d %s" % (errorcode, message)
row = cursor.next ()
# When the last row of the result set is reached,
# the next Method returns the value 'None'.
The for loop provides a particularly easy option for the common occurrence of iterating through a result set.
# To reference Python libraries:
# --------------------------------
import sys
import sapdb.sql
# To create an SQL session:
# ------------------------------------------------------
user_name, password, database_name = sys.argv [1:4]
session = sapdb.sql.connect (user_name, password, database_name)
select = """
SELECT msgno, language, msgtext FROM messages
WHERE msgno BETWEEN -1000 AND -1"""
# If the SQL method executes a SELECT statement,
# the result is an object of the SAPDB_ResultSet class.
cursor = session.sql (select)
# You can use a SapDB_ResultSet object in a for loop
# in the same way as any other iterator.
for row in cursor:
errorcode, language, message = row
print "%6d %s" % (errorcode, message)
# Both the execution of the SQL statement
# and the breakdown of a result row into columns
# can be defined compactly in a for statement.
for errorcode, language, message in session.sql (select):
print "%6d %s" % (errorcode, message)
The structure of a result set is not always known when it is written by the program. The getDescription method allows this structure to be determined at runtime.
# To reference Python libraries:
# --------------------------------
import sys
import sapdb.sql
# To create an SQL session:
# ------------------------------------------------------
user_name, password, database_name = sys.argv [1:4]
session = sapdb.sql.connect (user_name, password, database_name)
select = """
SELECT msgno, language, msgtext FROM messages
WHERE msgno BETWEEN -1000 AND -1"""
# If the SQL method executes a SELECT statement,
# the result is an object of the SAPDB_ResultSet class.
cursor = session.sql (select)
# The getDescription returns
# a list of the column descriptions.
descriptions = cursor.getDescription ()
for description in descriptions:
print '======================='
# Column name
print 'Name:', description [0]
# Column type as a character string
print 'Type:', description [1]
# Column type as an integer code
print 'Type:', description [2]
# Column length
print 'Len:', description [3]
# Number of decimal places
print 'Frac:', description [4]
# Result set columns are always required columns.
print 'Mandatory:', description [5]
# Result set columns are always output.
print 'in/out:', description [6]
If you want to execute the same SQL statement with different values, choose the prepare method. Using this method means that Python values do not need to be converted to the version understood by the SQL parser.
# To reference Python libraries:
# --------------------------------
import sys
import sapdb.sql
# To create an SQL session:
# ------------------------------------------------------
user_name, password, database_name = sys.argv [1:4]
session = sapdb.sql.connect (user_name, password, database_name)
#
# To delete and create a PYTEST test table:
#
try:
session.sql ("DROP TABLE PYTEST")
except sapdb.sql.SQLError:
pass
session.sql ("""CREATE TABLE PYTEST (
keycol VARCHAR (20),
datacol VARCHAR (100),
PRIMARY KEY (keycol),
CHECK datacol <> 'invalid' )
""")
# To generate an object of the SapDB_Prepared class:
insert = session.prepare ("INSERT INTO PYTEST VALUES (?, ?)")
for value in ['a', 'b', 'c']:
keyval = value + 'key'
dataval = value + 'data'
# The execute method executes the prepared
# SQL statement with the parameter list
insert.execute ([keyval, dataval])
for keyval, dataval in session.sql (
"SELECT * from PYTEST"):
print keyval, '=>', dataval
If an error occurs when processing an SQL statement, an exception of the sapdb.sql.SQLError class is generated.
# To reference Python libraries:
# --------------------------------
import sys
import sapdb.sql
# To create an SQL session:
# ------------------------------------------------------
user_name, password, database_name = sys.argv [1:4]
session = sapdb.sql.connect (user_name, password, database_name)
#
# To delete and create a PYTEST test table:
#
try:
session.sql ("DROP TABLE PYTEST")
except sapdb.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 sapdb.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 sapdb.sql.SQLError, err:
print "ERR [%d] %s" % (err.errorCode, err.message)