Click here to view and discuss this page in DocCommentXchange. In the future, you will be sent there automatically.

SQL Anywhere 12.0.0 (中文) » UltraLite - C 及 C++ 编程 » 应用程序开发 » 使用 UltraLite C++ API 开发应用程序 » 使用 SQL 语句访问数据

 

数据检索:SELECT

使用 SELECT 语句可从数据库中检索信息。执行 SELECT 语句时,PreparedStatement.ExecuteQuery 方法返回一个 ResultSet 对象。请参见ExecuteQuery 方法

 ♦  执行 SELECT 语句
  1. 使用以下代码声明所需的变量:

    ULPreparedStatement * prepStmt;
    ULResultSet * resultSet;
  2. 准备要执行的 SQL 语句。

    以下代码准备要执行的 SELECT 语句:

    prepStmt = conn->PrepareStatement("SELECT MyColumn1 FROM MyTable");
  3. 准备语句时检查错误。

    例如,以下代码适用于检查 SQL 语法错误:

    if( prepStmt == NULL ) {
        const ULError * ulerr;
        ulerr = conn->GetLastError();
        // write code to handle the error
        return;
    }
  4. 执行 SQL,并返回可用于移动查询结果的结果集对象。

    resultSet = prepStmt->ExecuteQuery();
    if( resultSet == NULL ) {
        const ULError * ulerr;
        ulerr = conn->GetLastError();
        // write code to handle the error
        prepStmt->Close();
        return;
    }
  5. 通过调用 Next 方法来遍历行。将结果以字符串存储在缓冲区中。

    Next 方法可移动到结果集的下一行。如果该调用返回 true,ULResultSet 对象定位在某一行上;否则,如果该调用返回 false,所有的行都已遍历。

    while( resultSet->Next() ) {
        char buffer[ 100 ];
        resultSet->GetString( 1, buffer, 100 );
        printf( "MyColumn = %s\n", buffer );
    }
  6. 清理预准备语句和结果集对象资源。

    调用 Close 方法后,不能再访问预准备语句对象。

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