id | title | brief |
---|---|---|
9A6AF59E-BAEE-03B3-03A4-94A235C27CBF |
Create a Database with SQLiteNET |
This recipe will demonstrate how to create an SQLite database with SQLite-NET. |
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.
- Create a new Xamarin.iOS application called
CreateDatabaseWithSqlitenet
.
- Add a reference to
System.Data
andMono.Data.SQLite
- 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*.
- 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.
- 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>();
}
- 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);
}
- Run the application. First click on the Create Database button to create the database and the schema:
- Now each time the Insert User button is clicked, another row is added to the Person table: