Contents Index Understanding UltraLite Development Accessing and manipulating data with dynamic SQL

Native UltraLite for Java User's Guide
  Understanding UltraLite Development

Connecting to a database


Any UltraLite application must connect to a database before it can carry out any operation on the data. This section describes how to write code to connect to an UltraLite database.

To connect to an UltraLite database

  1. Create a DatabaseManager object.

    You can create only one DatabaseManager object per application. This object is at the root of the object hierarchy. For this reason, it is often best to declare the DatabaseManager object global to the application.

    The following code creates a DatabaseManager object named dbMgr.

    DatabaseManager dbMgr = new DatabaseManager();

    For more details, see the code in Samples\NativeUltraLiteForJava\Simple\Simple.java under your SQL Anywhere directory, and ianywhere.native_ultralite.DatabaseManager in the API Reference.

  2. Declare a Connection object.

    Most applications use a single connection to an UltraLite database and keep the connection open all the time. Multiple connections are only required for multi-threaded data access. For this reason, it is often best to declare the Connection object global to the application.

    static Connection conn;
  3. Attempt to open a connection to an existing database.

  4. If no database exists, create a database and establish a connection to it.

Example 

The following code opens a connection to an UltraLite database named mydata.udb.

CreateParms parms = new CreateParms();
parms.databaseOnDesktop = "mydata.udb";
parms.schema.schemaOnDesktop = "mydata.usm";
try {
  conn = dbMgr.openConnection( parms );
  System.out.println(
    "Connected to an existing database." );
}
catch( SQLException econn ) {
  if( econn.getErrorCode() ==
      SQLCode.SQLE_DATABASE_NOT_FOUND ){
    conn = dbMgr.createDatabase( parms );
    System.out.println(
    "Connected to a new database." );
  } else {
    throw econn;
  }
}

In general, you will want to specify a more complete path to the file.

For more details, see the code in Samples\NativeUltraLiteForJava\Simple\Simple.java under your SQL Anywhere directory, and ianywhere.native_ultralite.DatabaseManager in the API Reference.

Using the Connection object 

Properties or methods of the Connection object govern global application behavior, including the following:

For more information, see Connection.SyncParms and Connection.SyncResult in the API Reference in the online documentation.

Multi-threaded applications 

Each Connection and all objects created from it should be used on a single thread. If you need to have multiple threads accessing the UltraLite database, then each thread should have its own connection.


Contents Index Understanding UltraLite Development Accessing and manipulating data with dynamic SQL