Está en la página 1de 13

MENU

Guides
Xamarin.Forms

Working with...

Working with a Local Database


Using SQLite.Net with Xamarin.Forms
PDF for offline use:
Download PDF

Sample Code:
Todo Sample

Related Samples:
Xamarin.Forms Samples

Let us know how you feel about this.


I love it!
I have a problem.

Xamarin.Forms apps can easily access local SQLite databases, using NuGets with PCL
solutions and compiler directives with Shared Projects.

Overview
This article describes how Xamarin.Forms applications can read and write data to a local
SQLite database using the SQLite.Net database layer. The approach for incorporating
SQLite.Net differs depending on the project template you select:

PCL Solutions PCL solutions can take advantage of the SQLite.NET PCL NuGet
packages to easily incorporate database operations into the shared code by
referencing the SQLite classes that ship in the NuGet. The Xamarin.Forms
DependencyService is used to create the platformspecific SQLite connection that is

required in this implementation.


Shared Projects Shared Projects can directly incorporate the SQLite.Net source from
GitHub and reference those SQLite classes. Compiler directives are used when
platformspecific code is required such as determining the location of the SQLite
data file.
The information below is focused on accessing a SQLite database using Xamarin.Forms.
For more information on working with SQLite.Net itself, refer to the Data Access: Using
SQLite.NET documentation. Most SQLite.Net code is sharable across all platforms; only
configuring the database connection and location of the SQLite database file requires
platformspecific functionality. This is explained below for each solution type.

Sample Code
The sample on GitHub is a simple Todolist application, and includes both PCL and
Shared Project examples. These screenshots show how the sample appears on each
platform:

The SQLite database engine is builtin to the iOS and Android operating systems. To
add SQLite support to Windows Phone projects follow the instructions at the end of
this article.

Using SQLite with PCL


The easiest way to use SQLite with Xamarin.Forms projects created from the Portable
Class Library PCL template is with the SQLite.Net NuGet packages. This section shows
how to add those packages to a Xamarin.Forms solution, wireup the database in
platformspecific code and use the DependencyService to utilize the connection in shared
code.

Xamarins.Forms PCL Project


To add SQLite support to a Xamarin.Forms PCL template solution, start with the shared
PCL library. Rightclick and choose Manage NuGet Packages... to add SQLite.Net support.

Use NuGet's search function to find SQLite.Net PCL and install the package as shown:

There are a number of NuGet packages with similar names, the correct package has these
attributes:
Created by: Frank A. Krueger
Id: sqlitenetpcl
NuGet link: sqlitenetpcl
Once the reference has been added, write an Interface to abstract any platformspecific
functionality. For SQLite.Net the only platformspecific work required is to determine the
location of the database file and create a connection. The interface used in the sample has
a single method defined:

publicinterfaceISQLite{
SQLiteConnectionGetConnection();
}

Once the interface has been defined, use the DependencyService to obtain an
implementation and get a valid SQLite database connection note that we have not
implemented this interface yet, that is covered in the following sections. The sample calls
the implementation in the TodoItemDatabase constructor:
publicTodoItemDatabase(){
database=DependencyService.Get<ISQLite>().GetConnection();
database.CreateTable<TodoItem>();
}

The remainder of the TodoItemDatabase contains queries against the SQLite


implementation. Example query code is shown below more details on the syntax can be
found in the Using SQLite.NET article.
publicIEnumerable<TodoItem>GetItems(){
return(fromiindatabase.Table<TodoItem>()selecti).ToList();
}
publicIEnumerable<TodoItem>GetItemsNotDone()
{
returndatabase.Query<TodoItem>("SELECT*FROM[TodoItem]WHERE[Done]=0");
}
publicTodoItemGetItem(intid)
{
returndatabase.Table<TodoItem>().FirstOrDefault(x=>x.ID==id);
}
publicintDeleteItem(intid)
{
returndatabase.Delete<TodoItem>(id);
}

The use of locks has been ommitted from the above code for clarity. See the sample
code itself for a simple approach to preventing concurrency issues by using a lock.

All the the data access code is written in the PCL library to be shared across all platforms.
Only the initial database setup requires platformspecific work, as outlined in the
following sections.

iOS Project
To configure the Xamarin.iOS application, add the same NuGet package to the iOS
project. This screenshot shows the NuGet window:

The only code required is the ISQLite implementation that determines the data file path
and creates a new connection. The following code places the SQLite database file in the
Library folder within the application's sandbox. See the iOS Working with the File System
documentation for more information on the different directories that are available for
storage.
[assembly:Dependency(typeof(SQLite_iOS))]
//...
publicclassSQLite_iOS:ISQLite{
publicSQLite_iOS(){}
publicSQLite.SQLiteConnectionGetConnection()
{
varsqliteFilename="TodoSQLite.db3";
stringdocumentsPath=Environment.GetFolderPath(Environment.SpecialFolder.
stringlibraryPath=Path.Combine(documentsPath,"..","Library");//Libraryfolder
varpath=Path.Combine(libraryPath,sqliteFilename);
//Createtheconnection
varconn=newSQLite.SQLiteConnection(path);
//Returnthedatabaseconnection
returnconn;
}}

Note that the code includes the assembly:Dependency atttribute so that this
implementation is discoverable by the DependencyService.

Android Project
Add the same SQLite.Net PCL library to the Android project, as shown in this NuGet
window screenshot:

Once this reference has been added, the only code required is the ISQLite
implementation that determines the data file path and creates a new connection.
[assembly:Dependency(typeof(SQLite_Android))]
//...
publicclassSQLite_Android:ISQLite{
publicSQLite_Android(){}
publicSQLite.SQLiteConnectionGetConnection(){
varsqliteFilename="TodoSQLite.db3";
stringdocumentsPath=System.Environment.GetFolderPath(System.Environment.
varpath=Path.Combine(documentsPath,sqliteFilename);
//Createtheconnection
varconn=newSQLite.SQLiteConnection(path);
//Returnthedatabaseconnection
returnconn;
}}

Windows Phone Project


Before adding SQLite.Net to a Windows Phone project ensure SQLite binaries have

been added via the SQLite for Windows Phone Extension following these
instructions.
Once the SQLite Extension has been added, add the SQLite.Net PCL NuGet to the
Windows Phone project. This screenshot shows the package in the NuGet window.

Once it has been added to the project, the only code required is the ISQLite
implementation that creates a new connection using a valid database file path. The code
below uses the Windows.Storage API to determine the default file location.
[assembly:Dependency(typeof(SQLite_WinPhone))]
//...
publicclassSQLite_WinPhone:ISQLite{
publicSQLite_WinPhone(){}
publicSQLite.SQLiteConnectionGetConnection(){
varsqliteFilename="TodoSQLite.db3";
stringpath=Path.Combine(ApplicationData.Current.LocalFolder.Path,sqliteFilename);
//Createtheconnection
varconn=newSQLite.SQLiteConnection(path);
//Returnthedatabaseconnection
returnconn;
}}

Windows and Windows Phone 8.1


Refer to the Xamarin.Forms for Windows samples for details on how to add SQLite to a
Windows Phone 8.1 or Windows 8.1 project.

Using SQLite with Shared Projects


To use SQLite with a Xamarin.Forms Shared Project template solution simply add the
SQLite.Net source code and implement a few lines

Shared Project
First, add the SQLite.cscode from GitHub to the Shared Project.
Because the Shared Project code is treated as part of each individual application project,
the TodoItemDatabase class can take advantage of compiler directives to perform platform
specific operations while sharing the remainder of the code in the class.
The only platformspecific code required is the calculation of the file path to store the
SQLite data file. This has been implemented in the sample using a private property that
encapsulates the code required for all platforms, as shown below:
stringDatabasePath{
get{
varsqliteFilename="TodoSQLite.db3";
#if__IOS__

stringdocumentsPath=Environment.GetFolderPath(Environment.SpecialFolder
stringlibraryPath=Path.Combine(documentsPath,"..","Library");//Libraryfol
varpath=Path.Combine(libraryPath,sqliteFilename);
#else
#if__ANDROID__
stringdocumentsPath=Environment.GetFolderPath(Environment.SpecialFolder
varpath=Path.Combine(documentsPath,sqliteFilename);
#else

//WinPhone
varpath=Path.Combine(ApplicationData.Current.LocalFolder.Path,sqliteFilename);
#endif
#endif
returnpath;
}
}

The remainder of the class is 100% shared across all platforms and is also the exact same
code that is used in the PCL sample.

publicIEnumerable<TodoItem>GetItems(){
return(fromiindatabase.Table<TodoItem>()selecti).ToList();
}
publicIEnumerable<TodoItem>GetItemsNotDone()
{
returndatabase.Query<TodoItem>("SELECT*FROM[TodoItem]WHERE[Done]=0");
}
publicTodoItemGetItem(intid)
{
returndatabase.Table<TodoItem>().FirstOrDefault(x=>x.ID==id);
}
publicintDeleteItem(intid)
{
returndatabase.Delete<TodoItem>(id);
}

The use of locks has been ommitted from the above code for clarity. See the sample
itself for a simple approach to preventing concurrency issues by using a lock.

iOS and Android Projects


Because the code in the Shared Project is compiled as though part of each application, no
additional code or configuration is required in the Xamarin.iOS or Xamarin.Android
projects.

Windows Phone Project


The only additional configuration required for the Windows Phone application referencing
a Shared Project is to add the SQLite Extension as shown in the Adding SQLite database
support to Windows Phone section below.

Adding SQLite database support to


Windows Phone

Windows Phone does not include the SQLite database engine by default, so you need to
ship it with your application. Follow these steps to add SQLite to a Windows Phone
application:
First, download the Precompiled Binaries for Windows Phone 8VISX download from the
SQLite website. The relevant section of the SQLite download page is shown here:

Once downloaded, doubleclick to install the Visual Studio extension. After it's installed
and Visual Studio has been restarted, rightclick the Xamarin.Forms Windows Phone
project and choose Add Reference....

In the Reference Manager select the Windows Phone SDK 8.0 section on the left, then tick

SQLite for Windows Phone from the Extensions list. If the SQLite option is not shown, the
SQLite VISX has not installed correctly or Visual Studio needs to be restarted.

The Windows Phone project will now have SQLite listed in the project References. This
provides SQLite database support equivalent to the iOS and Android platforms. Once this
has been installed in a Windows Phone project, return to either the PCL or Shared Project
instructions above.
For additional information on installing SQLite database support on Windows Phone, read
the Nokia docs or this helpful blog post.

Summary
Xamarin.Forms can easily support databasedriven applications using the SQLite database
engine that is builtin to iOS and Android, and which can easily be added to Windows
Phone. SQLite.Net makes it easy to load and save objects in shared code.

Previous

Files

Next

Behaviors

+1 855 9262746
Sitemap

Privacy policy

hello@xamarin.com
2016 Xamarin Inc.

También podría gustarte