Create a Database with SQLiteNET

PDF for offline use
Sample Code:

Let us know how you feel about this

Translation Quality


0/250

This recipe will demonstrate how to create an SQLite database with SQLite-NET.

Recipe

The following recipe provide some sample code for using SQLite-NET to create a database with a single table and then inserting rows into that table, highlighting the relevant parts.

  1. Create a new Xamarin.iOS application called CreateDatabaseWithSqlitenet.
  1. Add a reference to System.Data and Mono.Data.SQLite
  1. Add the Nuget package sqlite-net by Frank Krueger to your project by right-clicking on the Packages folder and selecting Add Packages. In the window that opens, search for SQLite.Net, select the package and click *Add Package*.

  1. Create a Person class that will represent a row inside an SQLite table named Person table:
public class Person
{
   [PrimaryKey, AutoIncrement]
   public int ID { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
}

SQLite-NET will create a table that will hold a Person object, with columns in the table for each of the properties in the Person class. The ID property of the class is adorned with the attributes PrimaryKey and AutoIncrement. These attributes are by SQLite-NET to generate the proper DDL statements to create the Person table.

  1. The snippet for creating the database with a Person table can be see in the file CreateDatabaseWithSqliteNet.cs, lines 82-85:
using (var conn= new SQLite.SQLiteConnection(_pathToDatabase))
{
   conn.CreateTable<Person>();
}
  1. The code for inserting a new Person row into the person table can be the file CreateDatabaseWithSqliteNet.cs, lines 98-102:
var person = new Person { FirstName = "John " + DateTime.Now.Ticks, LastName = "Doe"};
using (var db = new SQLite.SQLiteConnection(_pathToDatabase ))
{
    db.Insert(person);
}
  1. Run the application. First click on the Create Database button to create the database and the schema:

  1. Now each time the Insert User button is clicked, another row is added to the Person table:

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.