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.
1. Creating the Python file sample_5.py:
#
# To reference Python libraries:
# -------------------------------------------
import sys
import sapdb.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 = sapdb.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 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 all parameters on the list
insert.execute ([keyval, dataval])
for keyval, dataval in session.sql (
"SELECT * from PYTEST"):
print keyval, '=>', dataval
#
# Ending the session with the database instance
# -----------------------------------------------
session.release ()
2. To call the Python file sample_5.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_5.py MONA RED DEMODB