Interacting With Local Database in Xamarin.Forms
It's very common for a mobile application to use a local SQLite database. The combination of Sqlite.net and Xamarin.Forms makes this very easy. One of the reasons that we choose SQLite as our mobile database is that it's a single file and easily works across platforms. iOS and Android both have the SQLite database engine built in and access to the data is simplified by Xamarin's platform that comes with the SQLite Data Provider.
Here I'm showing how to create a small project to store my notes into the local database. In this app we can save data, view the saved data and also we can update and delete the saved data.
Before beginning to use it we must add the SQLite.Net-PCL NuGet package to the solution.
Add SQLite Net PCL NuGet package |
There is one more important task to do before coding, that is to add SQLite for Windows Phone . For that right-click on References in the Windows Phone project and select Add references.
Add References |
Now we can create a model in our shared project named NotesDB.cs.
Create a model in our shared project |
Here we want to use dependency services to define the path or location for our database to be saved and for the SQLite connection. For that I have created an interface INotes.cs.
Interface INotes |
Now we can implement each platform so that we can determine the data file path and create a new connection.
iOS Implementation
iOS Implementation |
Android Implementation
Android Implementation |
Windows Phone Implementation
Windows Phone Implementation |
Now let's add a bit of code for the manipulation of the database by creating a class NotesQuery.cs. The code for the manipulations is given below.
Getting connection and creating table
Getting connection and creating table |
Insert data
Insert Data |
Update data
Update Data |
Delete Data
Delete Data |