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

SQL Anywhere 11.0.1 (中文) » UltraLite - C 及 C++ 编程 » 教程:使用 C++ API 构建应用程序

 

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

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

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

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

    此过程执行以下任务。

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

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

      只有在关闭自动提交时才需要 commit 方法。缺省情况下,启用自动提交。但是为了获得更好的性能,或者为了进行多操作事务,可能会禁用自动提交。

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

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

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

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

    将如下行添加到 main() 方法中紧跟对 open_conn 的调用之后的地方。

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

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