Introduction

Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files is most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app.
Xamarin.Forms - SQLite Database CRUD Operations
SQLite
Xamarin.Forms - SQLite Database CRUD Operations
SQLite is a lightweight database that implements a small, fast, self-contained, high-reliability, full-featured, SQL database engine.
SQLite is the most used database in the world. It is built into all mobile phones.
Prerequisites
  • Visual Studio 2017 or Later(Windows or Mac)

Setting up a Xamarin.Forms Project

Start by creating a new Xamarin.Forms project. You’ll learn more by going through the steps yourself or download the source from here.
Visual Studio 2019 has more options in the opening window. Clone or check out the code from any repository or open a project or solution for your computer.
Now, you need to click "Create a new project".
Xamarin.Forms - SQLite Database CRUD Operations
Now, filter by Project Type: Mobile
Choose the Mobile App (Xamarin. forms) project under C# and Mobile.
Name your app. You probably want your project and solution to use the same name as your app. Put it on your preferred location for projects and click "Create".
Select the blank app and target platforms - Android, iOS and Windows (UWP).
Subsequently, go to the solution. In there, you get all the files and sources of your project (.NET Standard). Now, select XAML page and
double-click to open the MainPage.Xaml page.
You now have a basic Xamarin.Forms app. Click the "Play" button to try it out.

Setting up the User Interface

Go to MainPage.Xaml and write the following code.
MainPage.xaml
  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
  4. xmlns:local="clr-namespace:XamarinSQLite"
  5. x:Class="XamarinSQLite.MainPage">
  6. <StackLayout>
  7. <StackLayout>
  8. <StackLayout HorizontalOptions="Center" VerticalOptions="Start">
  9. <Image x:Name="imgBanner" Source="banner.png" ></Image>
  10. <Image Margin="0,0,0,10" HeightRequest="100" Source="SQLite.png" ></Image>
  11. <Label Margin="0,0,0,10" Text="SQLite" FontAttributes="Bold" FontSize="Large" TextColor="Gray" HorizontalTextAlignment="Center" ></Label>
  12. <Entry x:Name="txtPersonId" Placeholder="PersonId Update and Delete"></Entry>
  13. <Entry x:Name="txtName" Placeholder="Enter Person Name"></Entry>
  14. <StackLayout HorizontalOptions="CenterAndExpand" Orientation="Horizontal">
  15. <Button x:Name="btnAdd" WidthRequest="200" Text="Add" Clicked="BtnAdd_Clicked" />
  16. <Button x:Name="btnRead" WidthRequest="200" Text="Read" Clicked="BtnRead_Clicked" />
  17. </StackLayout>
  18. <StackLayout HorizontalOptions="CenterAndExpand" Orientation="Horizontal">
  19. <Button x:Name="btnUpdate" WidthRequest="200" Text="Update" Clicked="BtnUpdate_Clicked"/>
  20. <Button x:Name="btnDelete" WidthRequest="200" Text="Delete" Clicked="BtnDelete_Clicked" />
  21. </StackLayout>
  22. <ListView x:Name="lstPersons">
  23. <ListView.ItemTemplate>
  24. <DataTemplate>
  25. <TextCell Text="{Binding Name}" Detail="{Binding PersonID}"></TextCell>
  26. </DataTemplate>
  27. </ListView.ItemTemplate>
  28. </ListView>
  29. </StackLayout>
  30. </StackLayout>
  31. </StackLayout>
  32. </ContentPage>
Click the "Play" button to try it out.
Xamarin.Forms - SQLite Database CRUD Operations

NuGet Packages

Now, add the following NuGet Packages.
  • sqlite-net-pc
Add sqlite-net-pc NuGet
Go to Solution Explorer and select your solution. Right-click and select "Manage NuGet Packages for Solution". Search "sqlite-net-pc" and add Package. Remember to install it for each project (.NET Standard, Android, iO, and UWP).
Xamarin.Forms - SQLite Database CRUD Operations
Create a Model
In this step, you can create a model for deserializing your response.
Person.cs
  1. using SQLite;
  2. namespace XamarinSQLite
  3. {
  4. public class Person
  5. {
  6. [PrimaryKey, AutoIncrement]
  7. public int PersonID { get; set; }
  8. public string Name { get; set; }
  9. }
  10. }
Get Local File Path
Write the following code to get local file path for storing the database in App.xaml.cs
App.xaml.cs
  1. static SQLiteHelper db;
  2. public static SQLiteHelper SQLiteDb
  3. {
  4. get
  5. {
  6. if (db == null)
  7. {
  8. db = new SQLiteHelper(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "XamarinSQLite.db3"));
  9. }
  10. return db;
  11. }
  12. }
Create a Table
In this step, write the following code to create an SQLite Connection and create the table in SQLiteHelper.cs constructor.
SQLiteHelper.cs
  1. SQLiteAsyncConnection db;
  2. public SQLiteHelper(string dbPath)
  3. {
  4. db = new SQLiteAsyncConnection(dbPath);
  5. db.CreateTableAsync<Person>().Wait();
  6. }
Read All
Now, write the code to read all data from the SQLite Database.
SQLiteHelper.cs
  1. //Read All Items
  2. public Task<List<Person>> GetItemsAsync()
  3. {
  4. return db.Table<Person>().ToListAsync();
  5. }
MainPage.Xaml.cs
  1. protected async override void OnAppearing()
  2. {
  3. base.OnAppearing();
  4. //Get All Persons
  5. var personList = await App.SQLiteDb.GetItemsAsync();
  6. if(personList!=null)
  7. {
  8. lstPersons.ItemsSource = personList;
  9. }
  10. }
Click the "Play" button to try it out.
Xamarin.Forms - SQLite Database CRUD Operations
Insert
Now, write the following code to insert data into SQLite Database.
  1. //Insert and Update new record
  2. public Task<int> SaveItemAsync(Person person)
  3. {
  4. if (person.PersonID != 0)
  5. {
  6. return db.UpdateAsync(person);
  7. }
  8. else
  9. {
  10. return db.InsertAsync(person);
  11. }
  12. }
  13. private async void BtnAdd_Clicked(object sender, EventArgs e)
  14. {
  15. if (!string.IsNullOrEmpty(txtName.Text))
  16. {
  17. Person person = new Person()
  18. {
  19. Name = txtName.Text
  20. };
  21. //Add New Person
  22. await App.SQLiteDb.SaveItemAsync(person);
  23. txtName.Text = string.Empty;
  24. await DisplayAlert("Success", "Person added Successfully", "OK");
  25. //Get All Persons
  26. var personList = await App.SQLiteDb.GetItemsAsync();
  27. if (personList != null)
  28. {
  29. lstPersons.ItemsSource = personList;
  30. }
  31. }
  32. else
  33. {
  34. await DisplayAlert("Required", "Please Enter name!", "OK");
  35. }
  36. }
Click the "Play" button to try it out.
Xamarin.Forms - SQLite Database CRUD Operations
Read
Now, write the following code to read data from the SQLite Database.
  1. //Read Item
  2. public Task<Person> GetItemAsync(int personId)
  3. {
  4. return db.Table<Person>().Where(i => i.PersonID == personId).FirstOrDefaultAsync();
  5. }
  6. private async void BtnRead_Clicked(object sender, EventArgs e)
  7. {
  8. if (!string.IsNullOrEmpty(txtPersonId.Text))
  9. {
  10. //Get Person
  11. var person = await App.SQLiteDb.GetItemAsync(Convert.ToInt32(txtPersonId.Text));
  12. if(person!=null)
  13. {
  14. txtName.Text = person.Name;
  15. await DisplayAlert("Success","Person Name: "+ person.Name, "OK");
  16. }
  17. }
  18. else
  19. {
  20. await DisplayAlert("Required", "Please Enter PersonID", "OK");
  21. }
  22. }
Click the "Play" button to try it out.
Xamarin.Forms - SQLite Database CRUD Operations

Update
Now, write the following code to update the data in the SQLite Database.
  1. //Insert and Update new record
  2. public Task<int> SaveItemAsync(Person person)
  3. {
  4. if (person.PersonID != 0)
  5. {
  6. return db.UpdateAsync(person);
  7. }
  8. else
  9. {
  10. return db.InsertAsync(person);
  11. }
  12. }
  13. private async void BtnUpdate_Clicked(object sender, EventArgs e)
  14. {
  15. if (!string.IsNullOrEmpty(txtPersonId.Text))
  16. {
  17. Person person = new Person()
  18. {
  19. PersonID=Convert.ToInt32(txtPersonId.Text),
  20. Name = txtName.Text
  21. };
  22. //Update Person
  23. await App.SQLiteDb.SaveItemAsync(person);
  24. txtPersonId.Text = string.Empty;
  25. txtName.Text = string.Empty;
  26. await DisplayAlert("Success", "Person Updated Successfully", "OK");
  27. //Get All Persons
  28. var personList = await App.SQLiteDb.GetItemsAsync();
  29. if (personList != null)
  30. {
  31. lstPersons.ItemsSource = personList;
  32. }
  33. }
  34. else
  35. {
  36. await DisplayAlert("Required", "Please Enter PersonID", "OK");
  37. }
  38. }
Click the "Play" button to try it out.
Xamarin.Forms - SQLite Database CRUD Operations
Delete
Now, write the following code to delete data from SQLite Database.
  1. //Delete
  2. public Task<int> DeleteItemAsync(Person person)
  3. {
  4. return db.DeleteAsync(person);
  5. }
  6. private async void BtnDelete_Clicked(object sender, EventArgs e)
  7. {
  8. if (!string.IsNullOrEmpty(txtPersonId.Text))
  9. {
  10. //Get Person
  11. var person = await App.SQLiteDb.GetItemAsync(Convert.ToInt32(txtPersonId.Text));
  12. if (person != null)
  13. {
  14. //Delete Person
  15. await App.SQLiteDb.DeleteItemAsync(person);
  16. txtPersonId.Text = string.Empty;
  17. await DisplayAlert("Success", "Person Deleted", "OK");
  18. //Get All Persons
  19. var personList = await App.SQLiteDb.GetItemsAsync();
  20. if (personList != null)
  21. {
  22. lstPersons.ItemsSource = personList;
  23. }
  24. }
  25. }
  26. else
  27. {
  28. await DisplayAlert("Required", "Please Enter PersonID", "OK");
  29. }
  30. }
Click the "Play" button to try it out.

Xamarin.Forms - SQLite Database CRUD Operations
Full code

SQLiteHelper.cs
  1. using System.Threading.Tasks;
  2. using SQLite;
  3. namespace XamarinSQLite
  4. {
  5. public class SQLiteHelper
  6. {
  7. SQLiteAsyncConnection db;
  8. public SQLiteHelper(string dbPath)
  9. {
  10. db = new SQLiteAsyncConnection(dbPath);
  11. db.CreateTableAsync<Person>().Wait();
  12. }
  13. //Insert and Update new record
  14. public Task<int> SaveItemAsync(Person person)
  15. {
  16. if (person.PersonID != 0)
  17. {
  18. return db.UpdateAsync(person);
  19. }
  20. else
  21. {
  22. return db.InsertAsync(person);
  23. }
  24. }
  25. //Delete
  26. public Task<int> DeleteItemAsync(Person person)
  27. {
  28. return db.DeleteAsync(person);
  29. }
  30. //Read All Items
  31. public Task<List<Person>> GetItemsAsync()
  32. {
  33. return db.Table<Person>().ToListAsync();
  34. }
  35. //Read Item
  36. public Task<Person> GetItemAsync(int personId)
  37. {
  38. return db.Table<Person>().Where(i => i.PersonID == personId).FirstOrDefaultAsync();
  39. }
  40. }
  41. }
MainPage.Xaml.cs
  1. using Xamarin.Forms;
  2. namespace XamarinSQLite
  3. {
  4. public partial class MainPage : ContentPage
  5. {
  6. public MainPage()
  7. {
  8. InitializeComponent();
  9. }
  10. protected async override void OnAppearing()
  11. {
  12. base.OnAppearing();
  13. //Get All Persons
  14. var personList = await App.SQLiteDb.GetItemsAsync();
  15. if(personList!=null)
  16. {
  17. lstPersons.ItemsSource = personList;
  18. }
  19. }
  20. private async void BtnAdd_Clicked(object sender, EventArgs e)
  21. {
  22. if (!string.IsNullOrEmpty(txtName.Text))
  23. {
  24. Person person = new Person()
  25. {
  26. Name = txtName.Text
  27. };
  28. //Add New Person
  29. await App.SQLiteDb.SaveItemAsync(person);
  30. txtName.Text = string.Empty;
  31. await DisplayAlert("Success", "Person added Successfully", "OK");
  32. //Get All Persons
  33. var personList = await App.SQLiteDb.GetItemsAsync();
  34. if (personList != null)
  35. {
  36. lstPersons.ItemsSource = personList;
  37. }
  38. }
  39. else
  40. {
  41. await DisplayAlert("Required", "Please Enter name!", "OK");
  42. }
  43. }
  44. private async void BtnRead_Clicked(object sender, EventArgs e)
  45. {
  46. if (!string.IsNullOrEmpty(txtPersonId.Text))
  47. {
  48. //Get Person
  49. var person = await App.SQLiteDb.GetItemAsync(Convert.ToInt32(txtPersonId.Text));
  50. if(person!=null)
  51. {
  52. txtName.Text = person.Name;
  53. await DisplayAlert("Success","Person Name: "+ person.Name, "OK");
  54. }
  55. }
  56. else
  57. {
  58. await DisplayAlert("Required", "Please Enter PersonID", "OK");
  59. }
  60. }
  61. private async void BtnUpdate_Clicked(object sender, EventArgs e)
  62. {
  63. if (!string.IsNullOrEmpty(txtPersonId.Text))
  64. {
  65. Person person = new Person()
  66. {
  67. PersonID=Convert.ToInt32(txtPersonId.Text),
  68. Name = txtName.Text
  69. };
  70. //Update Person
  71. await App.SQLiteDb.SaveItemAsync(person);
  72. txtPersonId.Text = string.Empty;
  73. txtName.Text = string.Empty;
  74. await DisplayAlert("Success", "Person Updated Successfully", "OK");
  75. //Get All Persons
  76. var personList = await App.SQLiteDb.GetItemsAsync();
  77. if (personList != null)
  78. {
  79. lstPersons.ItemsSource = personList;
  80. }
  81. }
  82. else
  83. {
  84. await DisplayAlert("Required", "Please Enter PersonID", "OK");
  85. }
  86. }
  87. private async void BtnDelete_Clicked(object sender, EventArgs e)
  88. {
  89. if (!string.IsNullOrEmpty(txtPersonId.Text))
  90. {
  91. //Get Person
  92. var person = await App.SQLiteDb.GetItemAsync(Convert.ToInt32(txtPersonId.Text));
  93. if (person != null)
  94. {
  95. //Delete Person
  96. await App.SQLiteDb.DeleteItemAsync(person);
  97. txtPersonId.Text = string.Empty;
  98. await DisplayAlert("Success", "Person Deleted", "OK");
  99. //Get All Persons
  100. var personList = await App.SQLiteDb.GetItemsAsync();
  101. if (personList != null)
  102. {
  103. lstPersons.ItemsSource = personList;
  104. }
  105. }
  106. }
  107. else
  108. {
  109. await DisplayAlert("Required", "Please Enter PersonID", "OK");
  110. }
  111. }
  112. }
  113. }
I hope you have understood, how to use the SQLite Database with CRUD operations in Xamarin.Forms. Thanks for reading. Please share your comments and feedback.
Happy Coding :)