Fetching rows or columns from result sets in Python
After executing a statement that
returns one or more result sets, use one of the functions available
in the ibm_db API to iterate through the returned rows.
If
your result set includes columns that contain large data (such as
BLOB or CLOB data), you can retrieve the data on a column-by-column
basis to avoid large memory usage.
Before you begin
You must have a statement resource that is returned by either the ibm_db.exec_immediate or ibm_db.execute function that has one or more associated result sets.
Procedure
To fetch data from a result set:
Example
Example 1: Fetch rows from a result set by calling the ibm_db.fetch_both function
import ibm_db
conn = ibm_db.connect("database","username","password")
sql = "SELECT * FROM EMPLOYEE"
stmt = ibm_db.exec_immediate(conn, sql)
dictionary = ibm_db.fetch_both(stmt)
while dictionary != False:
print "The ID is : ", dictionary["EMPNO"]
print "The Name is : ", dictionary[1]
dictionary = ibm_db.fetch_both(stmt)
Example 2: Fetch rows from a result set by calling the ibm_db.fetch_tuple function
import ibm_db
conn = ibm_db.connect("database","username","password")
sql = "SELECT * FROM EMPLOYEE"
stmt = ibm_db.exec_immediate(conn, sql)
tuple = ibm_db.fetch_tuple(stmt)
while tuple != False:
print "The ID is : ", tuple[0]
print "The name is : ", tuple[1]
tuple = ibm_db.fetch_tuple(stmt)
Example 3: Fetch rows from a result set by calling the ibm_db.fetch_assoc function
import ibm_db
conn = ibm_db.connect("database","username","password")
sql = "SELECT * FROM EMPLOYEE"
stmt = ibm_db.exec_immediate(conn, sql)
dictionary = ibm_db.fetch_assoc(stmt)
while dictionary != False:
print "The ID is : ", dictionary["EMPNO"]
print "The name is : ", dictionary["FIRSTNME"]
dictionary = ibm_db.fetch_assoc(stmt)
Example 4: Fetch columns from a result set
import ibm_db
conn = ibm_db.connect("database","username","password")
sql = "SELECT * FROM EMPLOYEE"
stmt = ibm_db.exec_immediate(conn, sql)
while ibm_db.fetch_row(stmt) != False:
print "The Employee number is : ", ibm_db.result(stmt, 0)
print "The last name is : ", ibm_db.result(stmt, "LASTNAME")