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

SAP Sybase SQL Anywhere 16.0 (中文) » UltraLite - C 和 C++ 编程 » 教程:使用 C++ API 构建 Windows 应用程序

 

第 3 课:选择并列出表中的行

在本课中,您将从表中检索行并将它们打印到命令行。

前提条件

本课假定您已完成前面的所有课程。 请参见第 1 课:创建并连接到数据库

 任务
  1. 将以下方法添加到 customer.cpp 中紧靠 do_insert 方法之后的地方。此方法执行以下任务:

    • 打开 Table 对象。

    • 检索列标识符。

    • 将当前位置设置在表的第一行之前。

      对表的任何操作都在当前位置执行。此位置可以在表的第一行之前、某一行中或最后一行之后。缺省情况下(如在本例中),行按照其主键值 (cust_id) 进行排序。要按其它方式排序行,可以向 UltraLite 数据库添加索引,然后使用此索引打开表。

    • 对于每一行,将写出 cust_id 和 cust_name 值。循环一直执行到 Next 方法返回 false(检索完最后一行后发生此情况)。

    • 关闭 Table 对象。



    static bool do_select( ULConnection * conn )
    {
        ULTable * table = conn->OpenTable( "ULCustomer" );
        if( table == UL_NULL ) {
            return false;
        }
        ULTableSchema * schema = table->GetTableSchema();
        if( schema == UL_NULL ) {
            table->Close();
            return false;
        }
        ul_column_num id_cid = 
            schema->GetColumnID( "cust_id" );
        ul_column_num cname_cid = 
            schema->GetColumnID( "cust_name" );
        schema->Close();
    
        _tprintf( "\n\nTable 'ULCustomer' row contents:\n" );
        while( table->Next() ) {
            ul_char cname[ MAX_NAME_LEN ];
            table->GetString( cname_cid, cname, MAX_NAME_LEN );
            _tprintf( "id=%d, name=%s \n", (int)table->GetInt(id_cid), cname );
        }
        table->Close();
        return true;
    }
  2. 将以下行添加到 main 方法中紧靠对 insert 方法的调用之后的地方:

    do_select(conn);
  3. 通过运行 nmake 编译您的应用程序。

  4. 通过在命令提示符下键入 customer 运行应用程序。

结果

输出一个列表,其中列有 ULCustomer 表中的所有客户 ID 和客户名称。