Introduction
In this article, we are going to make our data persistence using SQLite in Xamarin.Forms. Firstly, we will setup SQLite db for our project, then make a table in it, and add some data in this table. After this, whenever we open our application, we will see that our data is now persisted and saved in local db of application.
Setup SQLite for your project
See this article to setup SQLite in your project or follow the steps blow:
Three steps are needed to setup SQLite db.
- Install sqlite-net-pcl into your solution from NuGet Package.
- Declare Interface in PCL project.
- Implement this interface in all three projects.
Firstly, install sqlite-net-pcl, then declare and implement interface. Details are given below.
Declaring Interface
- using SQLite;
- namespace XamarinApp1.Persistence
- {
- public interface ISQLiteDb
- {
- SQLiteAsyncConnection GetConnection();
- }
- }
Declare this interface in PCL.
Implement interface
Now, implement this interface in all three projects. By implementing this interface, you can set database path of each application. For Android and iOS code, it remains same but for Windows, it is slightly different.
For Android and iOS.
- using System;
- using SQLite;
- using XamarinApp1.Persistence;
- using System.IO;
- using Xamarin.Forms;
- using XamarinApp1.iOS.Persistence;
- [assembly: Dependency(typeof(SQLiteDb))]
- namespace XamarinApp1.iOS.Persistence
- {
- public class SQLiteDb : ISQLiteDb
- {
- public SQLiteAsyncConnection GetConnection()
- {
- var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
- var path = Path.Combine(documentsPath, "MySQLite.db3");
- return new SQLiteAsyncConnection(path);
- }
- }
- }
For Windows
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using SQLite;
- using XamarinApp1.Persistence;
- using Windows.Storage;
- using System.IO;
- using Xamarin.Forms;
- [assembly: Dependency(typeof(XamarinApp1.UWP.Persistence.SQLiteDb))]
- namespace XamarinApp1.UWP.Persistence
- {
- public class SQLiteDb : ISQLiteDb
- {
- public SQLiteAsyncConnection GetConnection()
- {
- string documentPath = ApplicationData.Current.LocalFolder.Path;
- string path = Path.Combine(documentPath, "MySQLite.db3");
- return new SQLiteAsyncConnection(path);
- }
- }
- }




Alain NataliniPosted Jul 6, 2017, 12:32 AM
Good job. I was going to write about this argument, but you wrote about it first.