## Executing an SQL Statement and Reading the Result Set with a For Loop

In this example you use the sql method. You execute a SELECT statement that returns an object of the class SapDB_ResultSet as a result (result set) and read the data records of the result set in a for loop.

### Procedure

...

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

#

# Import Python modules

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

import sys

import sdb.sql

#

# Connect to 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)

select = """

SELECT * FROM hotel.room"""

#

# Execute a SELECT statement

# Result: object of the class SAPDB_ResultSet

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

cursor = session.sql (select)

#

# You can use an object of the class SapDB_ResultSet in a for loop

# in the same way as any other iterator.

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

for row in cursor:

hno, type, free, price = row

print "%6d %s %d %6d" % (hno, type, free, price)

#

# You can use a for statement to

# execute an SQL statement and to group the result rows

# in columns.

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

for hno, type, free, price in session.sql (select):

print "%6d %s %d %6d" % (hno, type, free, price)

#

# Close connection to the database instance

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

session.release ()

2. Call the Python script:

python sample.py MONA RED DEMODB

### Result

10 double 45 200

10 single 20 135

20 double 13 100

20 single 10 70

30 double 15 80

30 single 12 45

[...]

See also:

Examples for the sdb.sql Module