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++ 编程 » API 参考 » 教程:使用 C++ API 构建应用程序

 

第 2 课:将数据插入数据库

以下过程介绍如何向数据库添加数据。

 ♦  向数据库添加行
  1. 将以下方法添加到 customer.cpp 中紧靠 main 方法之前的地方:



    static bool do_insert( ULConnection * conn ) 
    {
        ULTable * table = conn->OpenTable( "ULCustomer" );
        if( table == UL_NULL ) {
            _tprintf( "Table not found: ULCustomer\n" );
            return false;
        }
        if( table->GetRowCount() == 0 ) {
            _tprintf( "Inserting one row.\n" );
            table->InsertBegin();
            table->SetString( "cust_name", "New Customer" );
            table->Insert();
            conn->Commit();
        } else {
            _tprintf( "The table has %lu rows\n", table->GetRowCount() );
        }
        table->Close();
        return true;
    }

    此方法执行以下任务。

    • 使用 connection->OpenTable() 方法打开表。必须打开 Table 对象才能操作表。

    • 如果表为空,向表添加一行。为插入行,使用 InsertBegin 方法将代码更改为插入模式,为每个必需的列设置值,并执行插入操作将此行添加到数据库。

    • 如果此表非空,则报告表中的行数。

    • 关闭 Table 对象,释放相关资源。

    • 返回一个布尔值,指示操作是否成功。

  2. 调用已创建的 do_insert 方法。

    将以下行添加到 main() 方法中紧靠对 conn->Close 的调用之前的地方。

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

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