Google Windows 10 UWP SQLite: How to Store Data in DataBase for Beginners Tutorial(C#-XAML) | SubramanyamRaju Xamarin & Windows App Dev Tutorials

Thursday, 8 December 2016

Windows 10 UWP SQLite: How to Store Data in DataBase for Beginners Tutorial(C#-XAML)

Introduction:

If you want to implement sqlite database application for WinRT windowsphone 8.1, you may helped from my previous article. Now from this article we will learn about 'Sqlite support in Windows 10 UWP'. This article is compared with my previous articles, so that we can easily understand the changes in WP8.0, WP8.1 & Windows 10 UWP to setup Sqlite environment.

Note: If you are new to Windows 10 UWP app development, please read Windows 10 Beginners Guide.

Requirements:
  • This article is targeted for windows 10 Anniversary Update, so make sure you’ve downloaded and installed the latest Anniversary Windows 10 SDK from here.
  • We no longer need a developer license with Windows 10. But we must Enable Developer Mode to your device for development.
  • This post assumes you’re using Microsoft Visual Studio 2015 Update 3 or Later.
  • This article is developed on windows 10 machine.

Table of Contents: 

Some extensions to be installed in order to interact with Sqlite from your Windows 10 UWP app. And now it is very easy to setup sqlite environment in our apps. So this post covers all about sqlite with beginners level like this.
1. How to create new project with Windows 10 Anniversary SDK?
2. How to setup SQLite environment for UWP?
3. How to perform all SQLite CRUD operations ?
4. How to bind SQLite data to listbox?

Description:

SQLite is a very light weight database. In this tutorial I’ll be discussing how to write classes to handle all SQLite operations. So let's start with above hierarchy which is earlier discussed in "Table of Contents".
1. How to create new project With Windows 10 Anniversary SDK?
Before to use Windows 10 UWP Community Toolkit, first we need to create the new project. 
  • Launch Visual Studio 2015 Update 3 or Later
  • On the File menu, select New > Project.
  • The New Project dialog appears. The left pane of the dialog lets you select the type of templates to display. In the left pane, expand Installed > Templates Visual C# > Windows, then pick the Universal template group. The dialog's center pane displays a list of project templates for Universal Windows Platform (UWP) apps.
  • In the center pane, select the Blank App (Universal Windows) template. The Blank App template creates a minimal UWP app that compiles and runs but contains no user interface controls or data. You add controls to the app over the course of this tutorial. In the Name text box, type "SqliteUWP". Click OK to create the project.
Next dialog will ask for you to confirm that your app support min & target versions. For this sample, I target the app with minimum version 10.0.10240 like below:

2)How to setup SQLite environment?
Sqlite is directly not available in UWP, and don't worry now it is very easy to setup sqlite in Windows 10 UWP app. So we need to follow two steps only (i.e Installing SQLite for Universal Windows Platform SDK, Installing SQLite.Net-PCL package)

2.1)Installing SQLite for Universal Windows Platform SDK:
The first step is to install the SQLite for Universal Windows Platform SDK in the Visual Studio that you are using. To do that, click on TOOLS -> Extensions and Updates -> Online -> Then search for "SQLite for Universal Windows Platform". It should look like the following picture.
Click on Download and You can directly open it while downloading, authorize installation and click install when ready.
Open Solution explorer, right click on 'References' folder of your current project. Then add the reference to the "SQLite for Universal Windows Platform" library.
Also you need to add manually Visual C++ 2015 Runtime 


2.2)Installing SQLite.Net-PCL package:
After installing the library for SQLite, we need SQLite.Net-PCL NuGet package. With this library, we will be able to perform all the operations that you normally do in a database, such as Insert, Delete, Update and run search queries. Sqlite-net also offers an approach typical ORM. So to install it right click on your project (i.e in my case project name is SqliteUWP) =>Click on "Manage NuGet Packages" and search for "SQLite.Net-PCL"  => Click on "Install" button. After that we should found below dialog:

***Wow now whole SQLite set up process is completed, so now we are going to work with all CRUD operations***

3)How to perform all SQLite CRUD operations ?

Note: From this step on-wards, most of content will be same as my previous article. Please be note a few changes made in this post.

So its time to perform all SQLite CRUD(Create,Read,Update,Delete) operations. So my thought is in this sample i made one  single "DatabaseHelperClass.cs" class for whole application and handling the SQLite operations with this helper class. Lets see first my table structure first 

Here i am trying to create Table name is "Contacts" in "ContactsManager.sqlite" database. So my class "Contacts" with all getter and setter methods(Id,Name,PhoneNumber,CreatedDate) to maintain single contact as an object.
  1. public class Contacts  
  2. {  
  3.     //The Id property is marked as the Primary Key  
  4.     [SQLite.Net.Attributes.PrimaryKey, SQLite.Net.Attributes.AutoIncrement]  
  5.     public int Id { getset; }  
  6.     public string Name { getset; }  
  7.     public string PhoneNumber { getset; }  
  8.     public string CreationDate { getset; }  
  9.     public Contacts()  
  10.     {  
  11.         //empty constructor  
  12.     }  
  13.     public Contacts(string name, string phone_no)  
  14.     {  
  15.         Name = name;  
  16.         PhoneNumber = phone_no;  
  17.         CreationDate = DateTime.Now.ToString();  
  18.     }  
  19. }  

3.1)Writing DatabaseHelper Class to handle database operations(i.e CRUD)
  1. class DatabaseHelperClass  
  2.     {  
  3.         //Create Tabble   
  4.         public void CreateDatabase(string DB_PATH)  
  5.         {  
  6.             if (!CheckFileExists(DB_PATH).Result)  
  7.             {  
  8.                 using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), DB_PATH))  
  9.                 {  
  10.                     conn.CreateTable<Contacts>();  
  11.   
  12.                 }  
  13.             }  
  14.         }  
  15.         private async Task<bool> CheckFileExists(string fileName)  
  16.         {  
  17.             try  
  18.             {  
  19.                 var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);  
  20.                 return true;  
  21.             }  
  22.             catch  
  23.             {  
  24.                 return false;  
  25.             }  
  26.         } 
  27.  
  28.         // Insert the new contact in the Contacts table.   
  29.         public void Insert(Contacts objContact)  
  30.         {  
  31.             using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH))  
  32.             {  
  33.                 conn.RunInTransaction(() =>  
  34.                 {  
  35.                     conn.Insert(objContact);  
  36.                 });  
  37.             }  
  38.         } 
  39.  
  40.         // Retrieve the specific contact from the database.     
  41.         public Contacts ReadContact(int contactid)  
  42.         {  
  43.             using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH))  
  44.             {  
  45.                 var existingconact = conn.Query<Contacts>("select * from Contacts where Id =" + contactid).FirstOrDefault();  
  46.                 return existingconact;  
  47.             }  
  48.         } 
  49.  
  50.         public ObservableCollection<Contacts> ReadAllContacts()  
  51.         {  
  52.             try  
  53.             {  
  54.                 using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH))  
  55.                 {  
  56.                     List<Contacts> myCollection = conn.Table<Contacts>().ToList<Contacts>();  
  57.                     ObservableCollection<Contacts> ContactsList = new ObservableCollection<Contacts>(myCollection);  
  58.                     return ContactsList;  
  59.                 }  
  60.             }  
  61.             catch  
  62.             {  
  63.                 return null;  
  64.             }  
  65.   
  66.         } 
  67.  
  68.         //Update existing conatct   
  69.         public void UpdateDetails(Contacts ObjContact)  
  70.         {  
  71.             using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH))  
  72.             {  
  73.   
  74.                 var existingconact = conn.Query<Contacts>("select * from Contacts where Id =" + ObjContact.Id).FirstOrDefault();  
  75.                 if (existingconact != null)  
  76.                 {  
  77.   
  78.                     conn.RunInTransaction(() =>  
  79.                     {  
  80.                         conn.Update(ObjContact);  
  81.                     });  
  82.                 }  
  83.   
  84.             }  
  85.         }
  86.   
  87.         //Delete all contactlist or delete Contacts table     
  88.         public void DeleteAllContact()  
  89.         {  
  90.             using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH))  
  91.             {  
  92.   
  93.                 conn.DropTable<Contacts>();  
  94.                 conn.CreateTable<Contacts>();  
  95.                 conn.Dispose();  
  96.                 conn.Close();  
  97.   
  98.             }  
  99.         } 
  100.  
  101.         //Delete specific contact     
  102.         public void DeleteContact(int Id)  
  103.         {  
  104.             using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH))  
  105.             {  
  106.   
  107.                 var existingconact = conn.Query<Contacts>("select * from Contacts where Id =" + Id).FirstOrDefault();  
  108.                 if (existingconact != null)  
  109.                 {  
  110.                     conn.RunInTransaction(() =>  
  111.                     {  
  112.                         conn.Delete(existingconact);  
  113.                     });  
  114.                 }  
  115.             }  
  116.         }  
  117.     }  
  118. }
Also I created, below another helper class name is "ReadAllContactsList" that can read all contacts from DB 
  1. public class ReadAllContactsList  
  2.    {  
  3.        DatabaseHelperClass Db_Helper = new DatabaseHelperClass();  
  4.        public ObservableCollection<Contacts> GetAllContacts()  
  5.        {  
  6.            return Db_Helper.ReadAllContacts();  
  7.        }  
  8.    }  

4)How to bind SQLite  data to listbox?

In above step 3.1, I created one Database helper class name is "DatabaseHelperClass.cs" which is to perform all SQlite operations.

In the app.xaml class lets create a database. In the constructor we check if the database exists and if it does not we create it. Since if there is no file exists ,it will get an exception. 
  1. public static string DB_PATH = Path.Combine(Path.Combine(ApplicationData.Current.LocalFolder.Path, "ContactsManager.sqlite"));//DataBase Name   
  2.        public App()  
  3.        {  
  4.            this.InitializeComponent();  
  5.            this.Suspending += OnSuspending;  
  6.            if (!CheckFileExists("ContactsManager.sqlite").Result)  
  7.            {  
  8.                using (var db = new SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), DB_PATH))  
  9.                {  
  10.                    db.CreateTable<Contacts>();  
  11.                }  
  12.            }  
  13.        }  
  14.        private async Task<bool> CheckFileExists(string fileName)  
  15.        {  
  16.            try  
  17.            {  
  18.                var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);  
  19.                return true;  
  20.            }  
  21.            catch  
  22.            {  
  23.            }  
  24.            return false;  
  25.        }
  26. }
Next I divided my project into MVVM pattern for simplicity. So in Model folder I placed table class name is "Contacts.cs". In ViewModels I placed DB helpers classes(DatabaseHelperClass.cs & ReadAllContactsList.cs). And finally in Views folder I placed All my three UI related pages
  • AddConatct.xaml:This page for adding contact to database, when click on "Add Contact" button it will be add contact in database like this
  1. <Grid x:Name="LayoutRoot" Background="Transparent">  
  2.         <Grid.RowDefinitions>  
  3.             <RowDefinition Height="Auto"/>  
  4.             <RowDefinition Height="*"/>  
  5.         </Grid.RowDefinitions>  
  6.   
  7.         <!--TitlePanel contains the name of the application and page title-->  
  8.         <StackPanel Grid.Row="0" Margin="12,17,0,28">  
  9.             <TextBlock Text="Add Contact" Margin="9,-7,0,0"/>  
  10.         </StackPanel>  
  11.   
  12.         <!--ContentPanel - place additional content here-->  
  13.         <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">  
  14.             <StackPanel>  
  15.                 <TextBox Name="NametxtBx" Margin="10" Header="Name"/>  
  16.                 <TextBox InputScope="Digits" Name="PhonetxtBx" Margin="10" MaxLength="10" Header="PhoneNumber" />  
  17.                 <Button Content="Add Contact" Margin="10" HorizontalAlignment="Stretch" Click="AddContact_Click"/>  
  18.             </StackPanel>  
  19.         </Grid>  
  20.     </Grid>  




  1. private async void AddContact_Click(object sender, RoutedEventArgs e)  
  2.         {  
  3.             DatabaseHelperClass Db_Helper = new DatabaseHelperClass();//Creating object for DatabaseHelperClass.cs from ViewModel/DatabaseHelperClass.cs    
  4.             if (NametxtBx.Text != "" & PhonetxtBx.Text != "")   
  5.             {   
  6.                 Db_Helper.Insert(new Contacts(NametxtBx.Text, PhonetxtBx.Text));   
  7.                 Frame.Navigate(typeof(HomePage));//after add contact redirect to contact listbox page    
  8.             }   
  9.             else   
  10.             {   
  11.                 MessageDialog messageDialog = new MessageDialog("Please fill two fields");//Text should not be empty    
  12.                 await messageDialog.ShowAsync();   
  13.             }   
  14.         }
  • ReadContactList.xaml:This page for displaying all DB contact list with listbox.And in this screen there is two buttons(Add Contact & DeleteAll) for correspondingly add contact to DB / Delete entire table data.Firstly i made following listbox datatemplate for binding database contacts
  1. <!--LayoutRoot is the root grid where all page content is placed-->  
  2.     <Grid x:Name="LayoutRoot" Background="Transparent">  
  3.         <Grid.RowDefinitions>  
  4.             <RowDefinition Height="Auto"/>  
  5.             <RowDefinition Height="*"/>  
  6.         </Grid.RowDefinitions>  
  7.   
  8.         <!--TitlePanel contains the name of the application and page title-->  
  9.         <StackPanel Grid.Row="0" Margin="12,17,0,28">  
  10.             <TextBlock Text="Read All contacts with listbox" TextWrapping="Wrap" Margin="9,-7,0,0" FontSize="28"/>  
  11.         </StackPanel>  
  12.   
  13.         <!--ContentPanel - place additional content here-->  
  14.         <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">  
  15.             <Grid.RowDefinitions>  
  16.                 <RowDefinition Height="auto"/>  
  17.                 <RowDefinition Height="*"/>  
  18.             </Grid.RowDefinitions>  
  19.             <Grid Grid.Row="0">  
  20.                 <Grid.ColumnDefinitions>  
  21.                     <ColumnDefinition Width="*" />  
  22.                     <ColumnDefinition Width="*" />  
  23.                 </Grid.ColumnDefinitions>  
  24.                 <Button Grid.Column="0" Content="Add Contact"  Margin="5" HorizontalAlignment="Stretch" Click="AddContact_Click"/>  
  25.                 <Button Grid.Column="1" Name="btnDelete" IsEnabled="False" Content="DeleteAll" Margin="5" HorizontalAlignment="Stretch" Click="DeleteAll_Click"/>  
  26.             </Grid>  
  27.             <ListView BorderBrush="#FF141EE4"  Grid.Row="1" x:Name="listBoxobj" SelectionChanged="listBoxobj_SelectionChanged">  
  28.                 <ListView.ItemTemplate>  
  29.                     <DataTemplate>  
  30.                         <Grid>  
  31.                             <Border Margin="5" BorderBrush="White" BorderThickness="1">  
  32.                                 <Grid>  
  33.                                     <Grid.RowDefinitions>  
  34.                                         <RowDefinition Height="Auto"/>  
  35.                                         <RowDefinition Height="Auto"/>  
  36.                                     </Grid.RowDefinitions>  
  37.                                     <TextBlock Margin="5,0,0,0" Grid.Row="0" x:Name="NameTxt" TextWrapping="Wrap" Text="{Binding Name}" FontSize="28" Foreground="White"/>  
  38.                                     <TextBlock Grid.Row="0" Text=">" FontSize="28"  HorizontalAlignment="Right" VerticalAlignment="Center" Foreground="White"/>  
  39.                                     <TextBlock Margin="5,0,0,0" Grid.Row="1" x:Name="PhoneTxt"  TextWrapping="Wrap" Foreground="White" FontSize="18" Text="{Binding PhoneNumber}" />  
  40.                                     <TextBlock HorizontalAlignment="Right" Margin="0,0,35,0" Grid.Row="3" x:Name="CreateddateTxt" Foreground="White" FontSize="18" TextWrapping="Wrap" Text="{Binding CreationDate}" />  
  41.                                 </Grid>  
  42.                             </Border>  
  43.                         </Grid>  
  44.                     </DataTemplate>  
  45.                 </ListView.ItemTemplate>  
  46.                 <ListView.ItemContainerStyle>  
  47.                     <Style TargetType="ListViewItem">  
  48.                         <Setter Property="HorizontalContentAlignment" Value="Stretch" />  
  49.                     </Style>  
  50.                 </ListView.ItemContainerStyle>  
  51.             </ListView>  
  52.   
  53.         </Grid>  
  54.     </Grid>


So when page is loaded ,i done like this
  1. private void ReadContactList_Loaded(object sender, RoutedEventArgs e)  
  2.         {  
  3.             ReadAllContactsList dbcontacts = new ReadAllContactsList();  
  4.             DB_ContactList = dbcontacts.GetAllContacts();//Get all DB contacts    
  5.             if (DB_ContactList.Count > 0)  
  6.             {  
  7.                 btnDelete.IsEnabled = true;  
  8.             }  
  9.             listBoxobj.ItemsSource = DB_ContactList.OrderByDescending(i => i.Id).ToList();//Binding DB data to LISTBOX and Latest contact ID can Display first.    
  10.         }
When "Add Contact" button is clicked is navigated to "AddConatct.xaml" page to add contact in DB.
  1. private void AddContact_Click(object sender, RoutedEventArgs e)  
  2.         {  
  3.             Frame.Navigate(typeof(AddPage));  
  4.         }  
When "DeleteAll" button is clicked ,i done like this
  1. private void DeleteAll_Click(object sender, RoutedEventArgs e)  
  2.         {  
  3.             DatabaseHelperClass delete = new DatabaseHelperClass();  
  4.             delete.DeleteAllContact();//delete all DB contacts  
  5.             DB_ContactList.Clear();//Clear collections  
  6.             btnDelete.IsEnabled = false;  
  7.             listBoxobj.ItemsSource = DB_ContactList;  
  8.         }  
When selected listbox item ,i navigate to "DetailsPage.xaml" page for delete/update corresponding contact details on listbox SelectionChanged event  like this.

  1. private void listBoxobj_SelectionChanged(object sender, SelectionChangedEventArgs e)  
  2.         {  
  3.             if (listBoxobj.SelectedIndex != -1)  
  4.             {  
  5.                 Contacts listitem = listBoxobj.SelectedItem as Contacts;//Get slected listbox item contact ID  
  6.                 Frame.Navigate(typeof(DetailsPage), listitem);  
  7.             }  
  8.         }  
  • DetailsPage.xaml:This page is for updating/delete selected contact details
See in above when listbox item is selected ,i passed selected contact Id as query string,so in this i get that id in "OnNavigatedTo" method like this

  1. protected override void OnNavigatedTo(NavigationEventArgs e)  
  2.        {  
  3.            currentStudent = e.Parameter as Contacts;  
  4.            NametxtBx.Text = currentStudent.Name;//get contact Name  
  5.            PhonetxtBx.Text = currentStudent.PhoneNumber;//get contact PhoneNumber  
  6.        }  
When "Delete" button is pressed i done like this.
  1. private void DeleteContact_Click(object sender, RoutedEventArgs e)  
  2.         {  
  3.             Db_Helper.DeleteContact(currentStudent.Id);//Delete selected DB contact Id.  
  4.             Frame.Navigate(typeof(HomePage));  
  5.         }  
When "Update" button is pressed i done like this.
  1. private void UpdateContact_Click(object sender, RoutedEventArgs e)  
  2.         {  
  3.             currentStudent.Name = NametxtBx.Text;  
  4.             currentStudent.PhoneNumber = PhonetxtBx.Text;  
  5.             Db_Helper.UpdateDetails(currentStudent);//Update selected DB contact Id  
  6.             Frame.Navigate(typeof(HomePage));  
  7.         }
Important Note:
Please make sure to add reference of "Visual C++ 2015 Runtime" as discussed in step 2.1, otherwise you may get exception like "An exception of type "System.DllNotFoundException' occurred in SQLite.Net.Platform.WinRT.dll but not handled in user code".


 SQLiteUWPSample
Summary:
In this article, we have seen the basics of Sqlite, how to install the engine, the library Sqlite-net, and saw the most common operations (also known as code first), such as inserting, updating, and deleting data from a table of a database.

FeedBack Note: Please share your thoughts,what you think about this post,Is this post really helpful for you?otherwise it would be very happy ,if you have any thoughts for to implement this requirement in any another way?I always welcome if you drop comments on this post and it would be impressive.

Follow me always at  
Have a nice day by  :)

3 comments:

  1. NametxtBx.Text != "" & PhonetxtBx.Text != "" you forget &&
    thanks for the tutorial, it's nice an easy to understand

    ReplyDelete
  2. Thanks for the post, you have provided a simple step by step process so anyone can understand easily. For understanding Mobile Application Services and Android Development, you can visit Yberry Infosystem in Indore Visit: www.yberryinfosystem.com

    ReplyDelete
  3. Very much informative post sharing about the windows 10 using uwp sqlite, how to store data within it. Thanks a lot for the sharing. E-Commerce in Coimbatore | portal solutions in coimbatore

    ReplyDelete

Search Engine Submission - AddMe