You are on page 1of 11

16/9/2556

A new SQLite wrapper for Windows Phone 8 and Windows 8 The basics| qmatteoq.com

qmatteoq.com 4

Diary of a Windows Phone developer


About me Contact My MVP Profile My Nokia profile

2013,Jun

39 Comments Respond

A new SQLite wrapper for Windows Phone 8 and Windows 8 The basics
in Windows 8, Windows Phone , by qmatteoq

search something

SEARCH

Recent Posts
New reduced price to become a Windows Phone developer App Studio: lets take a look at a generated project App Studio: lets create our first application! App Studio: a new tool by Microsoft for Windows Phone developers New SDK update for Windows Phone 8

One of the topics that gathered more attention on my blog is SQLite: developing an application without the need to store, somehow, the data locally is almost impossible, so developers are always searching the best way to achieve this objective. SQLite is one of the most interesting solutions out there, since its open source and its available for almost every platform on the market (mobile, web, client, etc.). Ive already talked you about sqlite-net, a library that is available for Windows Phone 8 and Windows 8 that can be used to perform operations on a SQLite database using a high level API that support LINQ operations. This library is very simple to use, but it has some limitations: the biggest one is that doesnt support relationships out of the box. Now Peter Torr (a member of the Windows Phone development team in Microsoft) with the support of Andy Wigley (a former Windows Phone Development MVP that now has joined Microsoft) have released on Codeplex a new SQLite wrapper, that is totally different from sqlite-net and that satisfies another type of approach: total control. In fact, this new wrapper doesnt support any LINQ operation but only manual SQL statement: the biggest pro is that you can perform any type of operation, even managing relationships. The biggest cons is that youll have to rely on old plain SQL queries to do any operation, even the simplest ones, like creating a table or inserting some data. Lets see, step by step, how to use it and how the approach is different from using sqlite-net. In this first post were going to see the basics, in the next one well talk about relationships.

Recent Comments
qmatteoq on A new SQLite wrapper for Windows Phone 8 and Windows 8 The basics qmatteoq on How to display GIF images in a Windows Phone application qmatteoq on First steps with Caliburn Micro in Windows Phone 8 The first project Mahipatsinh on Working with SQLite in Windows Phone 8: a sqlite-net version for mobile Mayank Gupta on A new SQLite wrapper for Windows Phone 8 and Windows 8 The basics

Configure the wrapper


For the moment, since its written in native code, the library isnt available on NuGet: youll have to download the source code from the Codeplex page. The solution contains two projects: one is called SQLiteWinRT and the other one is called SQLiteWinRTPhone. The first one is for Windows Store apps, the second one for Windows Phone 8 apps (Windows Phone 7 is not supported, since it doesnt support native code): youll have to add to your solution the project that fits your needs. For this tutorial Im going to create a Windows Phone 8 application, so Im going to use the second project. Plus, as we did for sqlite-net, we need to install the official SQLite runtime, that is available as a Visual Studio extension: here is the link for the Windows Store apps version, here, instead, is the link for the Windows Phone 8 version. Now youre ready to use it! Were going to use the same sample we used in the sqlite-net post: a table to store data about people.

Archives
August 2013 July 2013 June 2013 May 2013 April 2013 March 2013 February 2013 January 2013 December 2012 November 2012 October 2012 September 2012 August 2012 July 2012 June 2012

Create the database


Lets see how to do it: private async void OnCreateDatabaseClicked(object sender, RoutedEventArgs e) { Database database = new Database(ApplicationData.Current.LocalFolder, "people.db"); await database.OpenAsync(); string query = "CREATE TABLE PEOPLE " + "(Id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + "Name varchar(100), " + "Surname varchar(100))"; await database.ExecuteStatementAsync(query); } First we create a new Database object, that were going to use to make operations on the database. There are various ways to instantiate it: in this sample were going to create it by specifying the folder in the isolated storage where to save the file and the

Tag Cloud App Studio Async Azure Caliburn Database Mangopollo Maps Microsoft
MVP

SQLite Telerik Unit testing

MVVM Nokia Panorama Skydrive

Windows 8 Windows

Phone Windows Phone 8


1/11

wp.qmatteoq.com/a-new-sqlite-wrapper-for-windows-phone-8-and-windows-8-the-basics/

16/9/2556

A new SQLite wrapper for Windows Phone 8 and Windows 8 The basics| qmatteoq.com
file name. The folder is passed to the constructor using a StorageFolder object, which is the Windows Runtime class that identifies a folder in the isolated storage. In the sample, were simply using the storages root. If the database doesnt exist, it will be created; otherwise it will simply be opened. Then we can open the connection, by calling the OpenAsync() method: it accepts, eventually, a parameter to set the opening mode (like read only). If we dont set it, it will be used the default one, that supports read and write operations. Then, we go manual! As already anticipated, the wrapper doesnt support LINQ operations, so youll have to write the needed SQL statements to perform the operation. I assume that you already know the basics of SQL, so I wont describe in details the queries: in this sample we define a query to create a table called People with 3 columns: Id (which is the primary key and its an auto increment value), Name and Surname (which simply contains strings). To execute the query we call the async method ExecuteStatementAsync() on the Database object, passing as parameter the string with the query statement. ExecuteStatementAsync() is the method we need to use when the query doesnt return any value and when we dont need to define any parameter (well see later how to use them). As you can see, theres a huge difference with the sqlite-net approach: theres no mapping with a class and theres no automatic conversion to a table. Everything is made with plain SQL statements.

Categories
Developer's life Uncategorized Windows 8 Windows Phone

Awards

Perform operations on the database


The approach to perform operations (insert, update, select, etc.) is the same weve seen: we open the connection, we define the query statement and we execute the query. The only difference is that when you do an insert, for example, usually you need to set some parameters, because some elements of the query are not fixed but dynamic. For example, if we want to add a new row in the People table weve created in the step before, we need to pass two dynamic values: Name and Surname . Here is the code to perform this operation: private async void OnAddDataClicked(object sender, RoutedEventArgs e) { Database database = new Database(ApplicationData.Current.LocalFolder, "people.db"); await database.OpenAsync(); string query = "INSERT INTO PEOPLE (Name, Surname) VALUES (@name, @surname)"; Statement statement = await database.PrepareStatementAsync(query); statement.BindTextParameterWithName("@name", "Matteo"); statement.BindTextParameterWithName("@surname", "Pagani"); await statement.StepAsync(); statement = await database.PrepareStatementAsync(query); statement.BindTextParameterWithName("@name", "John"); statement.BindTextParameterWithName("@surname", "Doe"); await statement.StepAsync(); } Please enter the Statement class, that can be used to perform additional operations on the query, like adding parameters and iterating over the results. To prepare a Statement object, youll need to call the PrepareStatementAsync() method passing as parameter the query to execute. How to manage parameters? The simplest way is to use named parameters, which can be added to a query simply by prefixing the @ symbol to the name of the parameter. In the sample, the insert query accepts two parameters: @name and @surname . How to define the value of these parameters? By calling the BindTextParameterWithName() method on the Statement object with two parameters: the first one is the name of the parameter, the second one is the value we want to assign. In the sample, were going to add two users to the table: one with name Matteo Pagani and one with name John Doe . To execute the query, we call the method StepAsync() on the Statement object. There are also other versions of the BindParameterWithName() method, according to the data type of the parameter (for example, if its a number you can use the method BindIntParameterWithName()). But the StepAsync() method has another purpose: it can be used also to iterate through the results of the query, in case were performing a query that can return one

wp.qmatteoq.com/a-new-sqlite-wrapper-for-windows-phone-8-and-windows-8-the-basics/

2/11

16/9/2556

A new SQLite wrapper for Windows Phone 8 and Windows 8 The basics| qmatteoq.com
or more values. Lets see, for example, how to perform a select to retrieve the data weve just inserted: private async void OnGetDataClicked(object sender, RoutedEventArgs e) { Database database = new Database(ApplicationData.Current.LocalFolder, "people.db"); await database.OpenAsync(); string query = "SELECT * FROM PEOPLE"; Statement statement = await database.PrepareStatementAsync(query); while (await statement.StepAsync()) { MessageBox.Show(statement.GetTextAt(0) + " " + statement.GetTextAt(1)); } } The first part of the code is the same weve seen before: we define the query (in this case, we retrieve all the rows of the People table), we prepare a Statement and we execute it with the StepAsync() method. The difference is that, this time, the StepAsync() method is performed into a while statement: its because the method will iterate over all the rows returned by the query so, every time we enter into the while loop, a new row is retrieved. In this sample, we expect to see the MessageBox twice: one for the user Matteo Pagani and one for the user John Doe . In the sample you see also how to get the values from the results: the Statement object offers some methods that starts with the Get prefix, that accepts as parameter the column index of the value to retrieve. There are some method for the most common data types: in this sample, since both Name and Surname are strings we use the GetTextAt() method, passing 0 as index to get the name and 1 as index to get the surname. Of course we can combine what weve learned in the last two samples and, for example, we can perform a select query that contains some parameters: private async void OnGetSomeDataClicked(object sender, RoutedEventArgs e) { Database database = new Database(ApplicationData.Current.LocalFolder, "people.db"); await database.OpenAsync(); string query = "SELECT * FROM PEOPLE WHERE Name=@name"; Statement statement = await database.PrepareStatementAsync(query); statement.BindTextParameterWithName("@name", "Matteo"); while (await statement.StepAsync()) { MessageBox.Show(statement.GetTextAt(0) + " " + statement.GetTextAt(1)); } } In this sample, we retrieve from the People table only the rows where the column Name contains the value Matteo. We have also another option to access to the columns of the rows weve retrieved with a query, but its disabled by default because it slower and it returns every value as string, instead of its proper type. To enable it you have to call the EnableColumnsProperty method of the Statement object: once youve done it, you can access to the values by using the Columns property of the Statement object: its a collection and you can access to each item by using the columns name as index. Here is a sample: private async void OnGetSomeDataWithColumnsPropertyClicked(object sender, RoutedEventArgs e) { Database database = new Database(ApplicationData.Current.LocalFolder, "people.db"); await database.OpenAsync(); string query = "SELECT * FROM PEOPLE"; Statement statement = await database.PrepareStatementAsync(query); statement.EnableColumnsProperty(); while (await statement.StepAsync()) { MessageBox.Show(statement.Columns["Name"] + " " + statement.Columns["Surname"]); } }

wp.qmatteoq.com/a-new-sqlite-wrapper-for-windows-phone-8-and-windows-8-the-basics/

3/11

16/9/2556

A new SQLite wrapper for Windows Phone 8 and Windows 8 The basics| qmatteoq.com

Coming soon
In this post weve learned the basic concepts to use this new wrapper to perform operations on a SQLite database and which are the differences with another popular wrapper, sqlite-net. In the next post well see how to deal with relationships, one of the most problematic scenarios to manage nowadays. Meanwhile, you can play with the sample project. Download the sample project Tagged with: SQLite Windows 8 Windows Phone

share to

t w fi at ct e ebr o o k + t h ti h si s
Buzz

39 Responses to A new SQLite wrapper for Windows Phone 8 and Windows 8 The basics

1.

Philip Colmer says:


June 6, 2013 at 11:35 am

I can see that you are specifying the folder to store the database in: Database database = new Database(ApplicationData.Current.LocalFolder, people.db); Does this mean that this wrapper allows you to save the database into, for example, the My Documents folder, something that sqlite-net cannot do? Im intrigued by this wrapper but it does seem like youve lost the power of mapping classes onto the database, or am I misunderstanding something here?
Reply

1.

qmatteoq says:
June 6, 2013 at 11:41 am

Hi Philip, honestly I havent tried, Ive played with this wrapper just with a Windows Phone 8 application, but I think it will work only if the database file is stored in the isolated storage. About the second question, youre totally right: this new wrapper works only in manual mode, with plain SQL queries. Theres no mapping with classes, there are no LINQ operations, just plain SQL statement and iteration over the results.
Reply

2.

Alex says:
June 26, 2013 at 3:49 pm

So how exactly does one decide on whether to go with sqlite-net or codeplex for a windows phone project?
Reply

1.

qmatteoq says:
June 27, 2013 at 2:38 pm

It all depends by your needs. If you have a simple app (for example, one table only) sqlite-net is much easier to use; if you need full control or you have a complex scenario (lot of tables, relationships, etc.) the new sqlite wrapper on codeplex is definitely better.
Reply

wp.qmatteoq.com/a-new-sqlite-wrapper-for-windows-phone-8-and-windows-8-the-basics/

4/11

16/9/2556

A new SQLite wrapper for Windows Phone 8 and Windows 8 The basics| qmatteoq.com

3.

prabhu says:
July 1, 2013 at 11:44 am

This database god compared to sqlite-net.In this database how to check table already created or not?
Reply

1.

qmatteoq says:
July 1, 2013 at 11:47 am

Hi, according to the SQLite documentation if you have to perform the following query: SELECT name FROM sqlite_master WHERE type=table AND name=table_name; Replace table_name with the name of the table you want to check.
Reply

1.

prabhu says:
July 1, 2013 at 12:23 pm

Hi,post my code check correct or not? this return column count=1. string test = Select name from sqlite_master where type=table and name=employeeRecord; var statement = await myDataBase.PrepareStatementAsync(test);
Reply

1.

qmatteoq says:
July 1, 2013 at 1:48 pm

I think yes, if it returns a value it means that the table exists; otherwise, the query would return no results.
Reply

1.

prabhu says:
July 1, 2013 at 2:35 pm

any time return same value .but i got solution another way while creating table itself use IF NOT EXISTS the problem will solved. sample : string createTable = create table if not exists employeeRecord + (RegNo integer primary key not null, + Name varchar(20), + City varchar(20));

wp.qmatteoq.com/a-new-sqlite-wrapper-for-windows-phone-8-and-windows-8-the-basics/

5/11

16/9/2556
4.

A new SQLite wrapper for Windows Phone 8 and Windows 8 The basics| qmatteoq.com
prabhu says:
July 1, 2013 at 2:41 pm

I will face another problem because While deleting particular row code will executed but table record is there. example code: string deleteQuery = delete from employeeRecord where RegNo=3; Statement statment = await myDataBase.PrepareStatementAsync(deleteQuery); MessageBox.Show(Deleted Successfully); this is correct or not?
Reply

1.

prabhu says:
July 1, 2013 at 3:03 pm

Sorry i got this problem i mised following commends: await statment.StepAsync(); thanks your cordination
Reply

1.

qmatteoq says:
August 4, 2013 at 7:54 pm

Sorry, but I think I didnt understand your question.


Reply

2.

qmatteoq says:
August 4, 2013 at 7:55 pm

Sorry, but I think I didnt understand your question.


Reply

5.

Derek says:
July 9, 2013 at 4:22 pm

With sqlite-net I used http://www.codeproject.com/Articles/13419/SelectQueryBuilder-Buildingcomplex-and-flexible-S to create queries. It might come in handy with this wrapper too.
Reply

6.

Neutobe says:
July 15, 2013 at 5:23 am

Is this native wrapper need biuld in arm same as sqlite-net-wp8?If so,the solution with this can not build in emulater,isnt it?
Reply

1.

qmatteoq says:
July 15, 2013 at 12:40 pm

I think yes, since its the SQLite runtime that requires two different compilations processes: one for ARM and one for X86. If you want to target the phone, youll need to build it for ARM; otherwise, if you want to deploy on the emulator, youll have to use X86.
Reply

wp.qmatteoq.com/a-new-sqlite-wrapper-for-windows-phone-8-and-windows-8-the-basics/

6/11

16/9/2556

A new SQLite wrapper for Windows Phone 8 and Windows 8 The basics| qmatteoq.com
1. Neutobe says:
July 16, 2013 at 9:12 am

X86? Why Sqlite in my solution is ARM and Win32?


Reply

2.

Neutobe says:
July 17, 2013 at 4:03 am

I just found my mistake.Thanks a lot.


Reply

7.

Alex says:
July 23, 2013 at 12:26 pm

So Im finally running my project and I get WinRT information: SQL Error. And Im not even sure where the error is coming from. Any suggestions qmatteoq?
Reply

1.

Alex says:
July 25, 2013 at 8:46 pm

After a couple of code changes, now it gives a System.ArgumentException on this line: Statement readStatement = await database.PrepareStatementAsync(query); which is really weird because I cant find anything wrong with that line
Reply

8.

Ashu says:
September 2, 2013 at 10:38 am

i have downloaded your code but i am unable to find the Database wrapper class. Can you please show us Database wrapper class ? and one thing more i would like to ask during building your code i am facing following error. App.xaml The name LocalizedStrings does not exist in the namespace clr-namespace:SQLiteNew. I had downloaded Sqlite new from link given by you in tutorial. I really like your post and it will solve my so much issue. Please rectify my issues. It will be great help.
Reply

1.

qmatteoq says:
September 4, 2013 at 2:12 pm

Hi, the Database class is part of the wrapper. Make sure that youve added, in your project, a reference to both SQLiteWrapper project and SQLite runtime (the one that is installed using the Visual Studio extension).
Reply

wp.qmatteoq.com/a-new-sqlite-wrapper-for-windows-phone-8-and-windows-8-the-basics/

7/11

16/9/2556
9.

A new SQLite wrapper for Windows Phone 8 and Windows 8 The basics| qmatteoq.com
Mayank Gupta says:
September 10, 2013 at 11:45 am

How to use the Windows phone 8 project. its not mentioned anywhere in your blog
Reply

1.

qmatteoq says:
September 10, 2013 at 11:47 am

Im sorry, but what do you mean exactly? This post is about using the new SQLite wrapper with a Windows Phone 8 project.
Reply

1.

Mayank Gupta says:


September 10, 2013 at 11:49 am

I want to know how will i use the sqlite wrapper for windows phone 8 in my app project. there are no steps mentioned on how will I include the sqlite wrapper in my project.
Reply

1.

qmatteoq says:
September 10, 2013 at 11:52 am

Hi, I guess you didnt read the post carefully The procedure is explained in the section titled Configure the wrapper.
Reply

1. says:

Mayank Gupta

September 10, 2013 at 11:57 am

I just wanted to say that, it will be difficult for a beginner to able to deduce how to add project into your solutions. For more clarity these steps can be added Right Click on you Solution>Add >Existing Project >select the SQLiteWinRTPhone.vcxproj

2.

qmatteoq says:
September 10, 2013 at 12:03 pm

Thanks for the feedback, Ill try to be more precise in the future. However, the post was targeted to developers that already has a basic development and Visual Studio knowledge: if a

wp.qmatteoq.com/a-new-sqlite-wrapper-for-windows-phone-8-and-windows-8-the-basics/

8/11

16/9/2556

A new SQLite wrapper for Windows Phone 8 and Windows 8 The basics| qmatteoq.com
developer doesnt know how to add a project to a solution, maybe there are a few steps that he should take before learning how to use SQLite in a Windows Phone app

10.

Mayank Gupta says:


September 10, 2013 at 12:11 pm

I am getting error while I am importing the SQLiteWinRTPhone.vcxproj in my app project. it says Unable to read the project file SQLiteWinRTPhone.vcxproj. Also it says The imported project C:\Program Files\Microsoft SDKs\Windows Phone\v8.0\ExtensionSDKs\SQLite.WP80\3.7.1.1\DesignTime\Common Configuration\Neutral\SQLite.QP80.props not found. The SQlite version I have downloaded for windows phone is 3.8.0.2. What to do now ?
Reply

1.

qmatteoq says:
September 10, 2013 at 12:15 pm

Unfortunately the SQLite library should match the installed SQLite runtime. You have to wait that the Codeplex project is updated or, otherwise, manually install an old SQLite runtime that matches (in your case, its 3.7.1.1).
Reply

1.

Mayank Gupta says:


September 10, 2013 at 12:19 pm

from where can I get old (3.7.1.1) SQLite Runtime


Reply

2.

Mayank Gupta says:


September 10, 2013 at 2:55 pm

I am able to include the SQLite wrapper project in my windows phone 8 app project by editing the SQLiteWinRTPhone.vcxproj and replacing the path for 3.1.17 to 3.8.0.2
Reply

1.

qmatteoq says:
September 10, 2013 at 2:58 pm

Good alternative, I was going to propose this solution since I cant find on the web the 3.7.1.1 SQLite Runtime for Windows Phone. Good catch, meanwhile Ill try to contact the wrappers team to understand if theyre planning to keep it updated.
Reply

wp.qmatteoq.com/a-new-sqlite-wrapper-for-windows-phone-8-and-windows-8-the-basics/

9/11

16/9/2556

A new SQLite wrapper for Windows Phone 8 and Windows 8 The basics| qmatteoq.com

11.

Mayank Gupta says:


September 10, 2013 at 3:41 pm

I built an app using this wrapper and when I tried to run the app on WP8 Simulator, it is giving an exception A first chance exception of type System.Reflection.TargetInvocationException occurred in mscorlib.ni.dll ion the statement await database.ExecuteStatementAsync(query);
Reply

1.

qmatteoq says:
September 12, 2013 at 9:45 am

If you have the chance, send me your project and Ill take a look.
Reply

12.

Mayank Gupta says:


September 12, 2013 at 9:40 am

Cant we use this wrapper in a Portable Class Library for Windows Phone 8 ?
Reply

1.

qmatteoq says:
September 12, 2013 at 9:44 am

Nope, because the wrapper is based on Windows Runtime APIs, which are not supported by Portable Class Libraries.
Reply

13.

Mayank Gupta says:


September 12, 2013 at 10:28 am

Are you aware of any solution, to use this wrapper in a PCL


Reply

1.

qmatteoq says:
September 14, 2013 at 3:18 pm

Hi, theres no solution, since sqlite-net (as every other native library) cant be reference in a PCL. What you can do is to write a add a shared interface in the PCL that describes the methods needed to access to the data: then, the specific project implements it using sqlite-net.
Reply

Leave a Reply
Your email address will not be published. Required fields are marked * Name * Email * Website

wp.qmatteoq.com/a-new-sqlite-wrapper-for-windows-phone-8-and-windows-8-the-basics/

10/11

16/9/2556

A new SQLite wrapper for Windows Phone 8 and Windows 8 The basics| qmatteoq.com
8+8=?(robot check) * Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Comment

qmatteoq.com,Windows Phone, Windows 8 and much more,powered by wordpress.org and MetroWP theme

wp.qmatteoq.com/a-new-sqlite-wrapper-for-windows-phone-8-and-windows-8-the-basics/

11/11

You might also like