Monotouch SQLite Example

Using SQLite databases with MonoTouch iPhone applications is surprisingly easy to do.  For this example I have created a small application which queries a SQLite database and displays a list of country names in a UITableView.  The sample project can be downloaded here.

Step 1 is to create an SQLite database.  To do this I use the free "SQLite database browser" tool.  As you can see I have created a single table with two fields and inserted a number of rows (all the countries I have worked in).

SQLite Database Browser

Once you have created the database, add it to your project and then set the properties for the database file as follows:

  • Build Action = Content
  • Copy to output directory = Copy Always

Next you need to add references for:

  • System.Data.dll
  • Mono.Data.SQLite.dll

After that the data access code is pretty straight forward as can be seen below:

var conn = new SqliteConnection("Data Source=ExampleDB");

using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText ="select CountryID, CountryName from Countries";
using(var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Country c = new Country(int.Parse(reader["CountryID"].ToString()),
(string)reader["CountryName"]);
_Countries.Add(c);
}

}
}

As you can see, the database access code is fairly standard! Run the sample project in the simulator and you should see the database contents displayed.

Simulator