35
Andy Wigley @andy_wigley Matthias Shapiro @matthiasshap Programming SQLite on Windows Phone 8.1 WinRT Apps + Silverlight 30 April 2014 Building Apps for Windows Phone 8.1 Jump Start

19 programming sq lite on windows phone 8.1

Embed Size (px)

DESCRIPTION

Building Apps for Windows Phone 8.1 Jump Start . Videos at: http://channel9.msdn.com/Series/Building-Apps-for-Windows-Phone-8-1

Citation preview

Page 1: 19   programming sq lite on windows phone 8.1

Andy Wigley @andy_wigleyMatthias Shapiro @matthiasshap

Programming SQLite on Windows Phone 8.1

WinRT Apps+ Silverlight

30 April 2014

Building Apps for Windows Phone 8.1 Jump Start

Page 2: 19   programming sq lite on windows phone 8.1

Why use a Database? Complex Schema

Numerous relationships and constraintsExample: Shopping List

7 tables100s of records5 foreign keys

ItemReferenceData

PK ItemId

ItemName ItemDescriptionFK1 CategoryId

Categories

PK CategoryId

CategoryName

Lists

PK ListId

ListName

ListItems

PK ListItemId

ListItemNameFK1 ListId Quantity Category DescriptionFK2 StoreId

Stores

PK StoreId

StoreName StoreLocationLat StoreLocationLong StoreAddressLine1 StoreAddressLine2 StoreAddressCity StoreAddressState StoreAddressCountry StoryAddressZip

Favorites

PK FavoriteItemId

FavoriteItemName FavoriteItemCategory FavoriteItemQuantity FavoriteItemDescriptionFK1 FavoriteItemListId FavoriteItemPhoto

History

PK HistoryItemId

HistoryItemName HistoryItemCategory HistoryItemQuantity HistoryItemDescriptioin HistoryItemDateAddedFK1 HistoryItemListId HistoryItemPhoto

Page 3: 19   programming sq lite on windows phone 8.1

Why use a Database? Reference Data

Huge amounts of static reference dataExample: dictionary app

3 tables1 table with 500k rows

Words

PK WordId

Word Pronunciation Definition AlternateSpellings Origin

Favorites

PK FavoriteId

FK1 WordId

History

PK HistoryItemId

FK1 WordId AddedDate

Page 4: 19   programming sq lite on windows phone 8.1

Why SQLite?

Worlds’ most popular databaseWidely used on iOS, Android, Python, Mono etc…Public DomainSmall, Fast, Reliable

Rich FeaturesEmbedded SQL in-process database engineRead/writes to ordinary file in local folderSupports multiple tables, indices, triggers and viewsCross-platform – freely copy database files between 32-bit and 64-bit, or little endian and big endian

ReliableReputation for being very reliableLarge automated test suiteAll transactions are ACID even if interrupted by system crashes or power failures

Page 5: 19   programming sq lite on windows phone 8.1

SQLite.org

Documentation

SQL Syntax

C/C++ API Reference

Source and tools download

Page 6: 19   programming sq lite on windows phone 8.1

Installing the SQLite Library

Extension SDKInstall from Visual StudioTools – Extensions and Updates…

Versions for:• Windows 8• Windows 8.1• Windows Phone 8• Windows Phone 8.1For Universal apps, install both Windows 8.1 and Windows Phone 8.1 Extension SDKs

Installs toC:\Program Files (x86)\Microsoft SDKs\Windows(PhoneApp)\v8.1\ExtensionSDKs\SQLite.WinRT81(.WP81)

Page 7: 19   programming sq lite on windows phone 8.1

.NET APIs

SQLite-NETLINQ syntax

Lightweight ORM

Similar to WP8 Local Database (LINQ to SQL)

SQLitePCLSQL statements

Thin wrapper around the SQLite C API

using (var db = new SQLitePCL.Database("demo.db")){       db.Open(); using (var stmt = db.PrepareStatement ("SELECT name, age FROM people"))     {          while (stmt.Step())   {              var name = stmt.GetTextAt(0);              var age = stmt.GetIntAt(1);      }  } }

var db =  new SQLite.SQLiteAsyncConnection(App.DBPath);

var _customer = await  (from c in db.Table<Customer>() where c.Id == customerId  select c).FirstOrDefaultAsync();

if (customer != null) {      var Id = _customer.Id;      var Name = _customer.Name;     }

Page 8: 19   programming sq lite on windows phone 8.1

For more on SQLite-NET

Windows Phone Developer Blog: using the SQLite database engine with Windows Phone 8 appshttp://bit.ly/Zxg2Ox

Tim Heuer: HOWTO: SQLite with Windows 8 appshttp://bit.ly/MuzL1e

ErikEJ: Getting Started with SQLite in Windows Store / WinRT appshttp://bit.ly/130PpGa

Page 9: 19   programming sq lite on windows phone 8.1

Installing SQLitePCL to your Solution

1. Add Reference to SQLite extension SDK

2. In Configuration Manager, change target platform to X86 or ARM

3. In ‘Manage NuGet Packages’, add reference to SQLitePCL package

Page 10: 19   programming sq lite on windows phone 8.1

Installing SQLite into your solution

demo

Page 11: 19   programming sq lite on windows phone 8.1

SQLiteWinRTThe basics

Page 12: 19   programming sq lite on windows phone 8.1

Defining tables

SQLitePCL is really a thin wrapper around the SQLite ‘C’ APIInteract with the database usingSQL statementsParameterized queries and statements

Page 13: 19   programming sq lite on windows phone 8.1

Create database and tables

private void LoadDatabase() { // Get a reference to the SQLite database conn = new SQLiteConnection("sqlitepcldemo.db");

string sql = @"CREATE TABLE IF NOT EXISTS Customer (Id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, Name VARCHAR( 140 ), City VARCHAR( 140 ), Contact VARCHAR( 140 ) );"; using (var statement = conn.Prepare(sql)) { statement.Step(); } }

Page 14: 19   programming sq lite on windows phone 8.1

Insert

// SqlConnection was opened in App.xaml.cs and exposed through property conn var db = App.conn;

try { using (var custstmt = db.Prepare("INSERT INTO Customer (Name, City, Contact) VALUES (?, ?, ?)")) { custstmt.Bind(1, customerName); custstmt.Bind(2, customerCity); custstmt.Bind(3, customerContact); custstmt.Step(); } } catch (Exception ex) { // TODO: Handle error }

Page 15: 19   programming sq lite on windows phone 8.1

Select public Customer GetCustomer(int customerId) { Customer customer = null; using (var statement = dbconn.Prepare("SELECT Id, Name, City, Contact FROM Customer WHERE Id = ?")) { statement.Bind(1, customerId); if (SQLiteResult.DONE == statement.Step()) { customer = new Customer() { Id = (long)statement[0], Name = (string)statement[1], City = (string)statement[2], Contact = (string)statement[3] }; } } return customer; }

Page 16: 19   programming sq lite on windows phone 8.1

Update

// See if the customer already exists var existingCustomer = GetCustomer(customer.Id); if (existingCustomer != null) { using (var custstmt = dbconn.Prepare("UPDATE Customer SET Name = ?, City = ?, Contact = ? WHERE Id=?"))

{ // NOTE when using anonymous parameters the first has an index of 1, not 0. custstmt.Bind(1, customer.Name); custstmt.Bind(2, customer.City); custstmt.Bind(3, customer.Contact); custstmt.Bind(4, customer.Id);

custstmt.Step(); } }

Page 17: 19   programming sq lite on windows phone 8.1

Delete

public void DeleteCustomer(int customerId) { using (var statement = dbconn.Prepare("DELETE FROM Customer WHERE Id = ?")) { statement.Bind(1, customerId); statement.Step(); } }

Page 18: 19   programming sq lite on windows phone 8.1

Demo

SQLite using SQLitePCL

Page 19: 19   programming sq lite on windows phone 8.1

Transactions, relations and other constraints

Page 20: 19   programming sq lite on windows phone 8.1

Transactions

No changes can be made to the database except within a transactionAny command that changes the database will automatically execute within a transaction if one is not already in effectTransactions can be started manually using the BEGIN TRANSACTION statementSuch transactions persist until the next COMMIT TRANSACTION or ROLLBACK TRANSACTIONTransaction will also rollback if the database is closed

Page 21: 19   programming sq lite on windows phone 8.1

Manual transaction using (var statement = dbconn.Prepare("BEGIN TRANSACTION")) { statement.Step(); } // Execute one or more statements… using (var custstmt = dbconn.Prepare("INSERT INTO Customer (Name, City, Contact) VALUES (?, ?, ?)")) { ... } using (var projstmt = dbconn.Prepare("INSERT INTO Project (Name, Title, DueDate, CustomerId) VALUES (?, ?, ?, ?)"))

{ ... }

// COMMIT to accept all changes or ROLLBACK TRANSACTION to discard pending changes using (var statement = dbconn.Prepare(“COMMIT TRANSACTION")) { statement.Step(); }

Page 22: 19   programming sq lite on windows phone 8.1

Relations

Parent – Child relationship between records in one table and those in anotherExample:

Each Customer has a collection of one or more Projects

Relationship represented in the database by a column in the child object which stores the ID of the parentForeign key constraints enforce the relationship and maintain db integrity

Customer

PK Id Name City Contact

Project

PK IdNameDescriptionDueDate

FK1 CustomerId

Project

PK IdNameDescriptionDueDate

FK1 CustomerId

Project

PK IdNameDescriptionDueDate

FK1 CustomerId

Customer

PK Id Name City Contact

Project

PK IdNameDescriptionDueDate

FK1 CustomerId

Project

PK IdNameDescriptionDueDate

FK1 CustomerId

Page 23: 19   programming sq lite on windows phone 8.1

Creating foreign key constraints

With SQLiteWinRT, FK constraint is defined in the CREATE TABLE statement

CREATE TABLE IF NOT EXISTS Project  (Id          INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,       CustomerId  INTEGER,              Name        VARCHAR( 140 ),                Description VARCHAR( 140 ),                       DueDate     DATETIME,             FOREIGN KEY(CustomerId) REFERENCES Customer(Id)              );

Page 24: 19   programming sq lite on windows phone 8.1

Enforcing foreign key constraintsDefining a foreign key constraint on the table is not enough!Foreign key constraints are disabled by default (for backwards compatibility)Must be enabled at runtime using a PRAGMA// Turn on Foreign Key constraints  sql = @"PRAGMA foreign_keys = ON";

using (var statement = dbconn.Prepare(sql)){ statement.Step();}

Page 25: 19   programming sq lite on windows phone 8.1

Other constraints

Type Description SQLiteWinRT

PRIMARY KEY Defines the column(s) of the primary key- 1 per table max

YesIn Column or Table definition in a CREATE TABLE SQL statement

UNIQUE Column constraint enforces unique values in that column

YesIn Column definition

NOT NULL Column constraint prevents null values

YesIn Column definition

CHECK Column or Table constraint: constraint expression is evaluated on every insert or update, and if ‘0’ returned, constraint fails

YesIn Column or Table definition

See http://sqlite.org/lang_createtable.html for more information

Page 26: 19   programming sq lite on windows phone 8.1

No column data type constraints!

SQLite does not enforce column data type constraintsIt uses dynamic typingAny data can be inserted into any columnCan put strings into integer columns, floating point numbers in Boolean columns, or dates in character columns

SQLite does use the declared type of a column as a hint that you prefer values in that formatFor example, if a column is of type INTEGER and you try to insert a string into that column, SQLite will attempt to convert the string into an integer. If it can, it inserts the integer instead. If not, it inserts the stringThis feature is called type affinity.

Page 27: 19   programming sq lite on windows phone 8.1

IndexesIndex is created automatically for PRIMARY KEY columnsImportant to create indices on foreign key columns or columns used to select records from large tables

// Create index on Foreign Key column  sql = @"CREATE INDEX IF NOT EXISTS fk_customer_project_idx  ON project (customerId) ASC";

using (var statement = dbconn.Prepare(sql)){ statement.Step();}

Page 28: 19   programming sq lite on windows phone 8.1

Demo

Working with foreign key constraints

Page 29: 19   programming sq lite on windows phone 8.1

tools

Page 30: 19   programming sq lite on windows phone 8.1

sqlite3.exe

Download command line tool from sqlite.org

Page 31: 19   programming sq lite on windows phone 8.1

IDEsFor those who prefer a GUI, see the list of IDEs at http://www.sqlite.org/cvstrac/wiki?p=ManagementTools

Popular ones include:SQLiteStudiohttp://sqlitestudio.pl/ SQLite Administratorhttp://sqliteadmin.orbmu2k.de/ SQLite Experthttp://www.sqliteexpert.com/

Page 32: 19   programming sq lite on windows phone 8.1

Useful debugging tool

Page 33: 19   programming sq lite on windows phone 8.1

Transferring databases from device to desktopUse Isolated Storage Explorer tool from the Windows Phone SDK at C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v8.1\Tools\IsolatedStorageExplorerTool

To download all files from emulator or device to folder on your PC:

ISETool.exe ts xd e9df6878-0aeb-497f-bcf4-65be961d5ccb c:\data\myfiles

e9df…5ccb - This is the GUID of the project. This is located in AppxManifest.xml for APPX projects and WMAppManifest.xml for XAP projects.

Page 34: 19   programming sq lite on windows phone 8.1

Demo

Tools

Page 35: 19   programming sq lite on windows phone 8.1

©2014 Microsoft Corporation. All rights reserved. Microsoft, Windows, Office, Azure, System Center, Dynamics and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.