Sie sind auf Seite 1von 21

Working with SQLite in Windows Phone 8

KASIDIT WIJITSOPON
M EG A G E N I U S CO. , LT D.

Requirement
- SQLite for Windows Phone SDK
- Git for Windows
- C++ Wrapper (sqlite-net-wp8)
- C# class (sqlite-net)

Installing SQLite for Windows


Phone SDK
1.
2.
3.
4.

Click on TOOLS
Extensions and Updates
Click on Online
Search for
SQLite for Windows Phone

Installing SQLite for Windows


Phone SDK

Add Reference
SQLite for Windows Phone SDK
1.
2.
3.

Click on Add Reference


Windows Phone -> Extensions
Select the SQLite for Windows Phone

Installing Git for Windows


1. Go to http://msysgit.github.io
2. Download and Install msysgit

Installing Git for Windows

Clone sqlite-net-wp8 wrapper


git clone https://github.com/peterhuene/sqlite-net-wp8.git
(or Download Zip)

Add existing project sqlite-net-wp8

Add reference sqlite-net-wp8


1. Click on Add Reference
2. Click on Solution
3. Select the "Sqlite" project

Installing sqlite-net package


1.
2.
3.
4.

Right click on the project


Click on Manage NuGet Packages
Search for sqlite-net
Click on Install

Create compilation symbol


1.
2.

Right click on the project -> Properties


Add ;USE_WP8_NATIVE_SQLITE

Any CPU problem

Sample use
1. Create a class which defines the table.

public class Person


{

[SQLite.PrimaryKey, SQLite.AutoIncrement]
public int Id { get; set; }
public string FirstName { get; set; }

public string LastName { get; set; }


}

Sample use
2. Create a database in the constructor (App.xaml.cs). If the database

exists and if it does not we create it.


public App()
{
..

string dbPath =
Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path,
"db.sqlite");
if (!FileExists("db.sqlite").Result)
{
using (var db = new SQLiteConnection(dbPath))
{ db.CreateTable<Person>(); }
}

Sample use
private async Task<bool> FileExists (string fileName)
{
var result = false;
try
{
var store = await
Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
result =true;

}
catch { }

return result;
}

Sample use
3. Create button

- Insert (btnInsert)
- Select (btnSelect)

Add Click Event


btnInsert : btnInsert_Click
btnSelect : btnSelect_Click

Sample use
4. Create method btnInsert_Click
private void btnInsert_Click (sender, RoutedEventArgs e)
{

using (var db = new SQLiteConnection(dbPath))


{
db.RunInTransaction(() =>
{
db.Insert(new Person() { FirstName = "Tan", LastName = "Kitty" });

});
}
}

Sample use
5. Create async method btnSelect_Click
private async void btnSelect_Click(object sender, RoutedEventArgs e)
{
SQLiteAsyncConnection conn = new SQLiteAsyncConnection(dbPath);
var persons = await conn.QueryAsync<Person>("SELECT * FROM Person");
foreach (var person in persons)

System.Diagnostics.Debug.WriteLine(person.Id + " / " +person.FirstName


+ " / " + person.LastName);
}

Sample use
5. Run Project
Click on Insert button.
Click on Select button.

#Thank You

Das könnte Ihnen auch gefallen