Before
you can perform any database operations, first open a connection
to the database file. A
SQLConnection
instance
is used to represent a connection to one or more databases. The
first database that is connected using a SQLConnection instance
is known as the “main” database. This database is connected using
the
open()
method (for synchronous execution mode)
or the
openAsync()
method (for asynchronous execution
mode).
If you open a database using the asynchronous
openAsync()
operation, register
for the SQLConnection instance’s
open
event in
order to know when the
openAsync()
operation completes.
Register for the SQLConnection instance’s
error
event
to determine if the operation fails.
The following example shows how to open an existing database
file for asynchronous execution. The database file is named “DBSample.db”
and is located in the user’s
Pointing to the application storage directory
.
// Include AIRAliases.js to use air.* shortcuts
var conn = new air.SQLConnection();
conn.addEventListener(air.SQLEvent.OPEN, openHandler);
conn.addEventListener(air.SQLErrorEvent.ERROR, errorHandler);
// The database file is in the application storage directory
var folder = air.File.applicationStorageDirectory;
var dbFile = folder.resolvePath("DBSample.db");
conn.openAsync(dbFile, air.SQLMode.UPDATE);
function openHandler(event)
{
air.trace("the database opened successfully");
}
function errorHandler(event)
{
air.trace("Error message:", event.error.message);
air.trace("Details:", event.error.details);
}
The following example shows how to open an existing database
file for synchronous execution. The database file is named “DBSample.db”
and is located in the user’s
Pointing to the application storage directory
.
// Include AIRAliases.js to use air.* shortcuts
var conn = new air.SQLConnection();
// The database file is in the application storage directory
var folder = air.File.applicationStorageDirectory;
var dbFile = folder.resolvePath("DBSample.db");
try
{
conn.open(dbFile, air.SQLMode.UPDATE);
air.trace("the database opened successfully");
}
catch (error)
{
air.trace("Error message:", error.message);
air.trace("Details:", error.details);
}
Notice
that in the
openAsync()
method call in the asynchronous
example, and the
open()
method call in the synchronous
example, the second argument is the constant
SQLMode.UPDATE
.
Specifying
SQLMode.UPDATE
for the second parameter
(
openMode
) causes the runtime to dispatch an error
if the specified file doesn’t exist. If you pass
SQLMode.CREATE
for
the
openMode
parameter (or if you leave the
openMode
parameter
off), the runtime attempts to create a database file if the specified
file doesn’t exist. However, if the file exists it is opened, which
is the same as if you use
SQLMode.Update
. You can
also specify
SQLMode.READ
for the
openMode
parameter
to open an existing database in a read-only mode. In that case data
can be retrieved from the database but no data can be added, deleted,
or changed.