Download presentation
Presentation is loading. Please wait.
1
CIS 136 Building Mobile Apps
Storage Options CIS 136 Building Mobile Apps
2
Storage Options Storage API
3
WebSQL Implements a simple database application Benefits
full-featured database tables accessed via SQL queries an embedded SQL database allows each application to have its own SQL database does not need to run on a server does not require any configuration Benefits Provides persistent data storage There is no size limitation on how much can be stored It provides the SQL syntax, so it is a very powerful tool for managing data
4
Sqlite Plug-in org.apache.cordova.storage
provides an API virtually identical to WebSQL The main differences are: It is available with support for the Windows platform It effectively has no size limitations It is available in the following variations: cordova-sqlite-storage - core version that relies on native SQLite implementation -only available for iOS and Android platforms cordova-sqlite-ext - extended version with additional features including support for Windows and REGEXP support on Android and iOS cordova-sqlite-evfree - similar to cordova-sqlite-ext but with improved memory handling
5
Methods openDatabase() – transaction()–
Creates a new SQLLite database or opens one that has already been created database is in persistent storage This method returns a database object that allows manipulation of the data transaction()– executes SQL statements using executeSql() if any statement fails, any changes that have been made are discarded (roll back)
6
openDatabase() method
Fours parameters db_name: name of the database – this is the filename given tio the database when its written to memory; text db_version: version number (usually 1.0); text db_display_name: display name for the database; text db_size: amount of space allocated to the database in bytes, As the database increases in size, the user may be prompted for permission
7
<script> // Wait for device API libraries to load document.addEventListener("deviceready", onDeviceReady, false); // device APIs are available function onDeviceReady() { var appDB = window.openDatabase(“myDB”,”1.0”,”notes”, ); //1MB } </script>
8
transaction() method unit of work that is performed against a database
creating a record, updating a record, or deleting a record from the table performs a transaction on the table important to control transactions to ensure data integrity and to handle database errors
9
transaction() method the returned Database object provides a transaction() method three parameters Transaction SQL function: SQL code to execute Usually contained in a function Receives a transaction object which is used to execute the SQL statements Executes a method called executeSql Error: function to execute if a transaction error occurs receives two objects First object – can be used to execute more SQL statements Second object – error object having a code and message property Success: function to execute if the transaction works (optional) Does not receive any objects NOTE: error function precedes success function
10
<script> document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { var appDB = window.openDatabase(“myDB”,”1.0”,”notes”, 1024*1024); //1MB appDB.transaction(txnSQLfunction,onTxnError,onTxnSuccess); } function txnSQLfunction(txn) { //SQL statements are coded here function onTxnError() { // the DB failed to create a transaction object function onTxnSuccess() // the DB created a transaction object and will execute txnSQLfunction </script>
11
Transaction error() method
function onTxnError(sqltext, err) { //txn object not created if (err) alert (“code: “ + err.code + “ msg: “ + err.message ); } Else alert(“Unknown error”);
12
Transaction success() method
function onTxnSuccess(txn,results) { //txn object created alert (“transaction object created”); }
13
Transaction SQL function
Receives txn object and does 2 things Builds a SQL statement the instructions for the database action Create table, Select, Insert, Update, Delete records Executes the SQL statement using the executeSql() method executeSql() has four parameters The SQL statement The values passed to the SQL statement (if any) Where to go if the SQL statement works (a Success function) Where to go if the SQL statement fails ( Error function)
14
Inside the Transaction SQL function
function CreateTable(txn) { var sqlStmt = "CREATE TABLE IF NOT EXISTS STUDENTS (StudentID TEXT, FirstName TEXT, LastName TEXT, TEXT)"; txn.executeSql(sqlStmt, [], onSqlSuccess(), onSqlError(); }
15
Syntax for Creating Tables
The "CREATE TABLE" command is used to create a new table in a SQLite database A CREATE TABLE command specifies the following attributes of the new table: The name of the new table The name of each column (field) in the table The declared data type of each column in the table A default value or expression for each column in the table (optional) A sort sequence (optional) a PRIMARY KEY for the table (optional) Whether the table is a WITHOUT ROWID table (a ROWID uniquely identifies each row ) A set of SQL constraints for each table SQLite supports UNIQUE, NOT NULL, CHECK and FOREIGN KEY constraints.
16
Data Types NULL INTEGER and NUMERIC REAL TEXT
The value is a NULL value. INTEGER and NUMERIC The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value. Boolean values are integers 0 and 1 Can store a date as an integer using date/time functions - as Unix Time, the number of seconds since :00:00 UTC. REAL The value is a floating point value, stored as an 8-byte IEEE floating point number Can store a date as a real number using date/time functions Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar TEXT The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF- 16LE) Can store a date as text using date/time functions ("YYYY-MM-DD HH:MM:SS.SSS"). BLOB. The value is a blob of data, stored exactly as it was input.
17
Affinities Storage class for a data type BLOB
REAL DOUBLE DOUBLE PRECISION FLOAT REAL NUMERIC DECIMAL(10,5) BOOLEAN DATE DATETIME NUMERIC INT INTEGER TINYINT SMALLINT MEDIUMINT BIGINT UNSIGNED BIG INT INT2 INT8 INTEGER CHARACTER(20) VARCHAR(255) VARYING CHARACTER(255) NCHAR(55) NATIVE CHARACTER(70) NVARCHAR(100) TEXT CLOB TEXT
18
Example CREATE TABLE COMPANY( ID INT PRIMARY KEY ASC NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL );
19
Step-by-Step
20
Methods 1. First instruction will be to openDatabase() –
Creates a new SQLite database or opens one that has already been created database is in persistent storage This method returns a database object that allows manipulation of the data var appDB = window.openDatabase(“myDB”,”1.0”,”notes”, ); 2. Next instruction will be the transaction()– Creates a transaction object that executes a function Function will contain SQL statements The first method is to create/open a table appDB.transaction(txnSQLFunc,onTxnError,onTxnSuccess); function txnSQLFunc() {//sql statements to create/open table }
21
Process so far… var appDB = window.openDatabase(“myDB”,”1.0”,”notes”, ); appDB.transaction(CreateTable,onTxError,onTxSuccess); function onTxError(tx,err) { console.log(“transaction object not created: Code: ” + err.code); } fuction onTxSuccess() { console.log(“Transaction object created”); function CreateTable(tx) var sqlString = ‘CREATE TABLE IF NOT EXISTS STUDENTS (StudentID TEXT PRIMARY KEY NOT NULL, FirstName TEXT, LastName TEXT, TEXT)’; tx.executeSql(sqlString, [], onSqlSuccess(), onSqlError();
22
Understanding executeSql()
Executes sql statements Four parameters SQL Statement – to execute against the database object the transaction is associated with Value – array of values passed to SQL statement Success function – Function that will execute if the SQL statement is sucessfully processed Error function –function that will execute if the SQL statement fails The success function is passed two parameters: a transaction object (which is used to execute additional SQL statements against the table) A results object which contains the results of the SQL operation The results object exposes the following properties: insertID: If the SQL statement was to insert a record, the ROW ID rowAffected: If the SQL statement selected, inserted, updated, or deleted records, the number of records affected Rows: An object containing the records returned by the SQ statement
23
example sqlSuccess function
function onSqlSuccess(tx,res) { // SQL statement worked if (res) // make sure a results object was returned console.log(“Insert ID: “ + res.insertID); console.log(“Rows affected: “ + res.rowAffected; if (res.rows) // if records were returned var numRecs = res.rows.length; if numRecs > 0 { for (var i=0; i< numrecs; i++) { // do something with each record }
24
SQL
25
Select Statement Retrieves records from a table Syntax:
SELECT * FROM table_name; Syntax for sorting records SELECT * FROM table_name ORDER BY column_name ASC|DESC, column_name ASC|DESC; Syntax for filtering records SELECT * FROM table_name WHERE column_name operator value [AND column_name operator value] [OR column_name operator value];
26
Insert Into Statement Adds a record to the table
Syntax INSERT INTO table_name (column1,column2,column3,...) VALUES (value1,value2,value3,...); Example function insertRecord(tx) { var str= “INSERT INTO Customers (CustomerName,Country) VALUES ('Tom Smith', 'Norway')”; tx.executeSql(str,[],onInsertSuccess,onInsertError); }
27
Insert Into Statement Example 2 function insertRecord(tx) {
var strName = document.getElementById(“custName”).value; var strCtry = document.getElementById(“custCtry”).value; var str= “INSERT INTO Customers (CustomerName,Country) VALUES (?,?)”; tx.executeSql(str,[strName,strCtry],onInsertSuccess,onInse rtError); }
28
Update Statement Updates a record that is in the table Syntax
UPDATE table_name SET column1=value1,column2=value2,... [WHERE some_column=some_value]; Example function updateRecord(tx) { var strName = document.getElementById(“custName”).value; var strCtry = document.getElementById(“custCtry”).value; var str= “UPDATE Customers SET CustomerName = strName,Country=strCtry WHERE Country=‘Norway’”; tx.executeSql(str,[],onUpdateSuccess,onUpdateError); }
29
Delete Statement Removes a record from the table Syntax
DELETE FROM table_name [WHERE some_column=some_value]; Example function deleteRecord(tx) { var str= “DELETE FROM Customers WHERE Country=‘Norway’”; tx.executeSql(str,[],onDeleteSuccess,onDeleteError); }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.