MIRA
Using a database (SQLite)

Contents

Overview

The database module contains classes and functions to create, alter and access databases.

The SQLite database

Classes for accessing SQLite databases are wrappers around the C library sqlite3 (see http://www.sqlite.org/). They allow executing commands and queries in an object-oriented way. SQLite databases are file-based and therefore allow easy copying of database files across multiple systems.

Opening, creating and altering a database

Since SQLite databases are file-based, one needs to remove an existing file before creating a new SQLite database.

remove("MyDatabase.sqlite");
SQLiteDB db("MyDatabase.sqlite");

Creating a SQLiteDB object opens the given database file if it exists or creates a new one. After the database is successfully opened, one can create and alter tables via executing statements.

db.exec("create table employee(number int, name char(20));");
db.exec("insert into employee values (1, 'Homer Simpson');");
db.exec("insert into employee values (2, 'Patrick Star');");
db.exec("insert into employee values (3, null);");

For a complete list of the SQLite syntax (SQLite understands most of the standard SQL language), see http://www.sqlite.org/lang.html

Accessing a database

The database needs to be opened for accessing it. One can execute queries on the database with the query method.

SQLiteQuery q = db.query("select * from employee order by 1;");
// loop over all result rows
while (!q.eof())
{
// get the value of the first column (employee id)
int id = q.getValue<int>(0);
// get the value of the second column (employee name)
// and give a default name if value in database is null
std::string name = q.getValue<std::string>(1, "DefaultIfNull");
// next row of query result
++q;
}