Retrieving data using SELECT

The SELECT statement allows you to retrieve information from the database. When you execute a SELECT statement, the PreparedStatement.ExecuteQuery method returns a ResultSet object.

 Execute a SELECT statement
  1. Declare the required variables using the following code:

    ULPreparedStatement * prepStmt;
    ULResultSet * resultSet;
  2. Prepare a SQL statement for execution.

    The following code prepares a SELECT statement for execution:

    prepStmt = conn->PrepareStatement("SELECT MyColumn1 FROM MyTable");
  3. Check for errors when preparing the statement.

    For example, the following code is useful when checking for SQL syntax errors:

    if( prepStmt == NULL ) {
        const ULError * ulerr;
        ulerr = conn->GetLastError();
        // write code to handle the error
        return;
    }
  4. Execute the SQL and return a result set object that can be used to move the results of the query.

    resultSet = prepStmt->ExecuteQuery();
    if( resultSet == NULL ) {
        const ULError * ulerr;
        ulerr = conn->GetLastError();
        // write code to handle the error
        prepStmt->Close();
        return;
    }
  5. Traverse the rows by calling the Next method. Store the result as a string and store them in a buffer.

    The Next method moves to the next row of the result set. The ULResultSet object is positioned on a row if the call returns true; otherwise, if the call returns false, all the rows have been traversed.

    while( resultSet->Next() ) {
        char buffer[ 100 ];
        resultSet->GetString( 1, buffer, 100 );
        printf( "MyColumn = %s\n", buffer );
    }
  6. Clean up the prepared statement and result set object resources.

    The prepared statement object should not accessed after the Close method is called.

    resultSet->Close();
    prepStmt->Close();
 See also