Procedure documentationExample: Executing an SQL Statement and Reading the Result Set Locate this document in the navigation structure

 

In this example, you use the sql method (SapDB_Session class) and the next method (SapDB_ResultSet class) of the sdb.sql module. You execute a SELECT statement that returns an object of the SapDB_ResultSet class as a result (result set), and read the data records of this result set.

Procedure

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

    Syntax Syntax

    1. #
      # Import Python modules
      # -------------------------------------------
      import sys
      import sdb.sql
      # Connect to the database
      # -------------------------------------------
      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 title, name, cno FROM hotel.customer
        WHERE cno BETWEEN 3000 AND 8000"""
      #
      # Execute a SELECT statement
      # Result: An object of the SapDB_ResultSet class
      # -----------------------------------------------
      cursor = session.sql (select)
      #
      # The next method reads the next data record
      # in the result set.
      # When the last row of the result set is reached,
      # the next method returns the value 'None'.
      # -----------------------------------------------
      row = cursor.next ()
      while row:
        title, name, cno = row
        print "%s %s %d" % (title, name, cno)
        row = cursor.next ()
      #
      # Close connection to the database
      # ---------------------------------------------
      session.release ()
      
    End of the code.
  2. Call the Python script:

    python sample.py MONA RED DEMODB

Result

Mrs Porter 3000

Mr Brown 3100

Company Datasoft 3200

Mrs Brian 3300

Mrs Griffith 3400

Mr Randolph 3500

Mrs Smith 3600

Mr Jackson 3700

Mrs Doe 3800

Mr Howe 3900

Mr Miller 4000

Mrs Baker 4100

Mr Peters 4200

Company TOOLware 4300

Mr Jenkins 4400