Download - 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
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
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
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
SQLite.org
Documentation
SQL Syntax
C/C++ API Reference
Source and tools download
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)
.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; }
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
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
Installing SQLite into your solution
demo
SQLiteWinRTThe basics
Defining tables
SQLitePCL is really a thin wrapper around the SQLite ‘C’ APIInteract with the database usingSQL statementsParameterized queries and statements
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(); } }
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 }
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; }
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(); } }
Delete
public void DeleteCustomer(int customerId) { using (var statement = dbconn.Prepare("DELETE FROM Customer WHERE Id = ?")) { statement.Bind(1, customerId); statement.Step(); } }
Demo
SQLite using SQLitePCL
Transactions, relations and other constraints
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
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(); }
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
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) );
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();}
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
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.
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();}
Demo
Working with foreign key constraints
tools
sqlite3.exe
Download command line tool from sqlite.org
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/
Useful debugging tool
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.
Demo
Tools
©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.