5.3 Example - Executing a Query With a Known Number of Placeholders

Table of Contents Previous Next


5 Building and Executing Dynamic SQL Statements : 5.3 Example - Executing a Query With a Known Number of Placeholders

This example demonstrates how to execute a query with a known number of input parameters, and with a known number of columns in the result set. This method uses the PREPARE statement to parse and plan a query, before opening a cursor and iterating through the result set.
The code sample begins by including the prototypes and type definitions for the C stdio, string, stdlib, stdbool, and sqlca libraries, and providing basic infrastructure for the program:
The example then sets up an error handler; ECPGPlus calls the handle_error() function whenever a SQL error occurs:
Next, the program uses a PREPARE statement to parse and plan a query that includes a single parameter marker - if the PREPARE statement succeeds, it will create a statement handle that you can use to execute the statement (in this example, the statement handle is named stmtHandle). You can execute a given statement multiple times using the same statement handle.
The program then declares and opens the cursor, empCursor, substituting a user-provided value for the parameter marker in the prepared SELECT statement. Notice that the OPEN statement includes a USING clause: the USING clause must provide a value for each placeholder found in the query:
The application calls the handle_error() function whenever it encounters a SQL error. The handle_error() function prints the content of the error message, resets the error handler, rolls back any changes, disconnects from the database, and terminates the application.

5 Building and Executing Dynamic SQL Statements : 5.3 Example - Executing a Query With a Known Number of Placeholders

Table of Contents Previous Next