Using prepared statements

Prepared statements can be used to perform INSERT, UPDATE, and DELETE functions efficiently and to pass binary data as parameters. The encapsulates prepared statement functionality in the ITStatement class.

The following excerpts illustrate the use of the loadtab.cpp example to load a table from a text file by using a prepared statement.
  1. To use a prepared statement, the application creates an instance of ITStatement on the opened connection.
    ITStatement stmt(conn);
  2. The application prepares the SQL statement, which creates the statement parameters.
    if(!stmt.Prepare(sql))
        return -1;

    Created parameters have the value NULL.

  3. When the application must set a parameter value, it obtains the ITValue* of the parameter through the call to the Param() function.
    ITValue *param = stmt.Param(paramno);

    The application can call the NumParams() function to obtain the number of parameters.

  4. The application sets the parameter value by using ITValue::FromPrintable(), or it obtains the required interface by calling the QueryInterface() function and uses its update routines.
    if (!param->FromPrintable(pdb))
        {
        cerr << "Could not set parameter " 
             << paramno << " to '" << pdb << "'" << endl;
        return -1;

    The application must release the ITValue interface of the parameter by calling param->Release().

  5. After all parameter values are set, the application executes the prepared query.
    if (!stmt.Exec())
    {
        cerr << "Could not execute statement" << endl;
        return -1;

The application can use the RowCount() function to determine the number of rows affected by the last query executed. The application can then reset the parameter values and re-execute the query. Any parameter values that have not been reset stay the same.

After the application is completed work with the prepared statement, it drops the statement by using the Drop() function.

The same instance of ITStatement can be used to prepare another SQL statement by calling Prepare(), which calls Drop() for any currently prepared statement.