Databases Reference
In-Depth Information
Example 4-15 Using a cursor
EXEC SQL DECLARE c1 CURSOR FOR SELECT PID from inventory where
location='Store';
EXEC SQL OPEN c1;
EXEC SQL FETCH c1 INTO :PID;
printf("%s\n",PID);
EXEC SQL CLOSE c1;
EXEC SQL COMMIT;
In Example 4-15, a cursor named c1 is declared to hold a resultset of product
IDs. To use the cursor, the cursor is opened and data is retrieved into the PID
host variable. Once we are finished processing the resultset, the cursor should
be closed and a COMMIT executed to release any resources held.
In the inventory program we are developing, we need to retrieve information
about a single product. Because products are unique within the INVENTORY
table, we will only be retrieving one row back from the database (if the product
exists). This means that instead of a cursor, we can use a SELECT INTO
statement which will directly populate the host variables. A sample session from
querying a product is shown in Example 4-16. The complete definition of the
query_product() function is shown in Example 4-17 on page 165.
Example 4-16 Sample session querying a product in the inventory program
-------------------------------------------------
SIMPLE INVENTORY MANAGEMENT SYSTEM
1. Add New Product
2. Update Product Info (Quantity or Location)
3. Query Product
4. Exit
Enter option: 3
-------------------------------------------------
Query A Product
Enter Product ID : 101-101-10
Found Quantity : 50
Location : Warehouse
-------------------------------------------------
Search WWH ::




Custom Search