Skip to content

Adding a SQLite database to Xamarin.Forms

SQLite Logo
Source: Wikipedia (https://en.wikipedia.org/wiki/SQLite)

SQLite is an excellent choice for local storage within a mobile application. It is lightweight and with virtually zero configuration. Adding SQLite to a Xamarin.Forms project is fairly straightforward:

1. Add the nuget package SQLite-net PCL to each project (PCL, Android, & iOS)
Author = Frank A Krueger
ID = sqlite-net-pcl

2. Add an interface to the PCL project called: ISQLiteService.cs

3. Add a class to the iOS project called: SQLiteService.cs

4. Add a class to the Android project also called SQLiteService.cs

5. Add a class to the PCL project called: BaseItem.cs

6. Add a class to the PCL project called: Database.cs

7. To create a table model, simply create a class with public properties (with getters and setters) of the types and names of each field in the table. The class should inherit from BaseItem; this adds an auto incrementing ID field.

8. Create an instance of Database.cs called: database
To create a table simply call database.CreateTable();

Xamarin.Forms SQLiteExample ScreenshotYou now have a fully functioning database in Forms. To see a database in action, checkout out my example project on GitHub.

 

If you have any comments, questions, or suggestions, feel free to leave a comment below.

Published inDatabaseDependency ServiceFormsXamarin
  • Zahir khan

    its quite a comprehensive post , im gonna take a lot of time understanding everything , any idea on how to use an existing database , instead of creating one ?

  • Alex Little

    If I create a new database object from the database class whenever I need to use it (one instance per class/page) it will handle the threads correctly right?

  • Samuel Rule

    Absolutely fantastic guide this is the third or fourth time I have implemented this type of database and it ALWAYS causes me a headache. I came across this guide this time and it explains it very well. The code snippets were awesome, using generics makes for a much simpler implementation. Thank you very much 😀

    Its a year old but if anyone comes across it I recommend

  • Dzatara

    Amazing tutorial! best on the net so far
    Quick question…
    “BaseItem”… where does it inherit from?
    I’m getting an error in the “saveItem” method

    thanks

  • Karthik_k

    Tutorial is nice..
    But i have small question ?
    connection reference for sqlconnection showing null?