Skip to content
This repository has been archived by the owner on Oct 20, 2022. It is now read-only.

Latest commit

 

History

History

create_a_database_with_sqlitenet

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
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.

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*.
[![](Images/nuget_install.png)](Images/nuget_install_big.png) ![](Images/nuget_result.png)
  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: