Connecting to a database

UltraLite applications must connect to the database before performing operations on its data. This section describes how to connect to an UltraLite database.

The ULDatabaseManager class is used to open a connection to a database. The ULDatabaseManager class returns a non-null ULConnection object when a connection is established. Use the ULConnection object to perform the following tasks:

  • Commit or roll back transactions.

  • Synchronize data with a MobiLink server.

  • Access tables in the database.

  • Work with SQL statements.

  • Handle errors in your application.

For more information about the ULConnection class, see ULConnection class.

 iPhone database file

You can find sample code in the samples-dir\UltraLite\CustDB\ directory.

 To connect to an UltraLite database
  1. Initialize the ULDatabaseManager object and enable features in UltraLite using the following code:

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

    For more information about the ULDatabaseManager class, see ULDatabaseManager class.

  2. Open a connection to an existing database or create a new database if the specified database file does not exist using the following code:



    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 );

    In this step, you declare a ULError object that contains error information in case the connection is not successful. For more information about the ULError class, see ULError class.

 Multi-threaded applications