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.
2. Add a reference to System.Dataand Mono.Data.SQLite
3. Download the file SQLite.cs from, and copy it into the project directory. Add the file to the project:
4. Create a Person class that will represent a row inside an SQLite table namedPerson 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.
5. 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>(); }
6. 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); }
7. Run the application. First click on the Create Database button to create the database and the schema:
8. Now each time the Insert User button is clicked, another row is added to the Person table:
