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 开发应用程序

 

连接到数据库

UltraLite 应用程序必须先连接到数据库,然后才能对数据库中的数据进行操作。本节将介绍如何连接到 UltraLite 数据库。

ULDatabaseManager 类用于打开与数据库的连接。建立连接时,ULDatabaseManager 类返回非空的 ULConnection 对象。使用 ULConnection 对象执行以下任务:

  • 提交或回退事务。

  • 将数据与 MobiLink 服务器同步。

  • 访问数据库中的表。

  • 使用 SQL 语句。

  • 处理应用程序中的错误。

有关 ULConnection 类的详细信息,请参见ULConnection 类

 iPhone 数据库文件

可以在 samples-dir\UltraLite\CustDB\ 目录中找到示例代码。

 ♦  连接到 UltraLite 数据库
  1. 使用以下代码初始化 ULDatabaseManager 对象和启用 UltraLite 中的功能:

    if( !ULDatabaseManager::Init() ) {
        return 0;
    }
    ULDatabaseManager::EnableAesDBEncryption();
     
    // Use ULDatabaseManager.Fini() when terminating the app.

    有关 ULDatabaseManager 类的详细信息,请参见ULDatabaseManager 类

  2. 使用以下代码,打开与现有数据库的连接,或者,如果指定的数据库文件不存在,创建一个新数据库:



    ULConnection * conn;
    ULError ulerr;
     
    conn = ULDatabaseManager::OpenConnection( "dbf=sample.udb;dbkey=aBcD1234", &ulerr );
    if( conn == NULL ) {
        if( ulerr.GetSQLCode() == SQLE_ULTRALITE_DATABASE_NOT_FOUND ) {
            conn = ULDatabaseManager::CreateDatabase( "dbf=sample.udb;dbkey=aBcD1234", &ulerr );
            if( conn == NULL ) {
                // write code that uses ulerr to determine what happened
                return 0;
            }
            // add code to create the schema for your database
        } else {
            // write code that uses ulerr to determine what happened
            return 0;
        }
    }
    assert( conn != NULL );

    在此步骤中,万一连接不成功,则声明包含错误信息的 ULError 对象。有关 ULError 类的详细信息,请参见ULError 类

 多线程应用程序