CIS 136 Building Mobile Apps

Slides:



Advertisements
Similar presentations
Database Chapters.
Advertisements

Copyright © by Royal Institute of Information Technology Introduction To Structured Query Language (SQL) 1.
Day 3 - Basics of MySQL What is MySQL What is MySQL How to make basic tables How to make basic tables Simple MySQL commands. Simple MySQL commands.
MySQL-Database Teppo Räisänen Oulu University of Applied Sciences School of Business and Information Management.
Creating Database Tables CS 320. Review: Levels of data models 1. Conceptual: describes WHAT data the system contains 2. Logical: describes HOW the database.
SQLLite and Java CS-328 Dick Steflik. SQLLite Embedded RDBMS ACID Compliant Size – about 257 Kbytes Not a client/server architecture –Accessed via function.
SQLite 1 CS440. What is SQLite?  Open Source Database embedded in Android  SQL syntax  Requires small memory at runtime (250 Kbytes)  Lightweight.
Phonegap Bridge – File System CIS 136 Building Mobile Apps 1.
DATABASES AND SQL. Introduction Relation: Relation means table(data is arranged in rows and columns) Domain : A domain is a pool of values appearing in.
Introduction to SQL  SQL or sequel  It is a standardised language with thousands of pages in the standard  It can be in database system through GUI,
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor Ms. Arwa.
 SQL stands for Structured Query Language.  SQL lets you access and manipulate databases.  SQL is an ANSI (American National Standards Institute) standard.
CHAPTER:14 Simple Queries in SQL Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
Introduction to MySQL Lab no. 10 Advance Database Management System.
Web Scripting [PHP] CIS166AE Wednesdays 6:00pm – 9:50pm Rob Loy.
CSC 2720 Building Web Applications Database and SQL.
SQL SQL Server : Overview SQL : Overview Types of SQL Database : Creation Tables : Creation & Manipulation Data : Creation & Manipulation Data : Retrieving.
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Christopher M. Pascucci.NET Programming: Databases & ADO.NET.
Phonegap Bridge – File System CIS 136 Building Mobile Apps 1.
SQL Basics. What is SQL? SQL stands for Structured Query Language. SQL lets you access and manipulate databases.
Visual Programing SQL Overview Section 1.
Sql DDL queries CS 260 Database Systems.
SQLite DB Storing Data in Android RAVI GAURAV PANDEY 1.
>> Introduction to MySQL. Introduction Structured Query Language (SQL) – Standard Database Language – Manage Data in a DBMS (Database Management System)
1 CS 430 Database Theory Winter 2005 Lecture 11: SQL DDL.
Relational Database Management System(RDBMS) Structured Query Language(SQL)
Ch 3. Working with Tables and Views. Data type Specify type of data to be entered into a column (text, number, datetime, etc) Unicode (National) Datatypes.
LECTURE FOUR Introduction to SQL DDL with tables DML with tables.
MySQL Tutorial. Databases A database is a container that groups together a series of tables within a single structure Each database can contain 1 or more.
CHAPTER 9 File Storage Shared Preferences SQLite.
Phonegap Bridge – Storage CIS 136 Building Mobile Apps 1.
 MySQL is a database system used on the web  MySQL is a database system that runs on a server  MySQL is ideal for both small and large applications.
Web Database Programming Using PHP
Creating Database Objects
Fundamentals of DBMS Notes-1.
Web Systems & Technologies
Cosc 5/4730 Sqlite primer.
Chapter 5 Introduction to SQL.
CS320 Web and Internet Programming SQL and MySQL
Managing Tables, Data Integrity, Constraints by Adrienne Watt
MySQL-Database Jouni Juntunen Oulu University of Applied Sciences
SQL and SQL*Plus Interaction
Introduction to Structured Query Language(SQL)
Web Database Programming Using PHP
SQL – Data types.
Data Definition and Data Types
CIS 136 Building Mobile Apps
ISC440: Web Programming 2 Server-side Scripting PHP 3
CIS16 Application Programming with Visual Basic
SQL OVERVIEW DEFINING A SCHEMA
Database systems Lecture 2 – Data Types
CIS 136 Building Mobile Apps
CIS 136 Building Mobile Apps
Introduction To Structured Query Language (SQL)
CIS16 Application Programming with Visual Basic
Session - 6 Sequence - 1 SQL: The Structured Query Language:
CS3220 Web and Internet Programming SQL and MySQL
Chapter 4 Introduction to MySQL.
MySQL Database System Installation Overview SQL summary
IST 318 Database Administration
CS3220 Web and Internet Programming SQL and MySQL
Session - 6 Sequence - 1 SQL: The Structured Query Language:
Department of School of Computing and Engineering
SQLLite and Android.
Creating Database Objects
Database Instructor: Bei Kang.
JDBC II IS
SQL (Structured Query Language)
Introduction to SQL Server and the Structure Query Language
Presentation transcript:

CIS 136 Building Mobile Apps Storage Options CIS 136 Building Mobile Apps

Storage Options Storage API

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

Sqlite Plug-in org.apache.cordova.storage https://www.sqlite.org/lang.html 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

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)

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

<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”, 1048576); //1MB } </script>

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

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

<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>

Transaction error() method function onTxnError(sqltext, err) { //txn object not created if (err) alert (“code: “ + err.code + “ msg: “ + err.message ); } Else alert(“Unknown error”);

Transaction success() method function onTxnSuccess(txn,results) { //txn object created alert (“transaction object created”); }

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)

Inside the Transaction SQL function function CreateTable(txn) { var sqlStmt = "CREATE TABLE IF NOT EXISTS STUDENTS (StudentID TEXT, FirstName TEXT, LastName TEXT, Email TEXT)"; txn.executeSql(sqlStmt, [], onSqlSuccess(), onSqlError(); }

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.

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 1970-01-01 00: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.

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

Example CREATE TABLE COMPANY( ID INT PRIMARY KEY ASC NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL );

Step-by-Step

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”, 1048576); 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 }

Process so far… var appDB = window.openDatabase(“myDB”,”1.0”,”notes”, 1048576); 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, Email TEXT)’; tx.executeSql(sqlString, [], onSqlSuccess(), onSqlError();

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

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 }

SQL

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];

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); }

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); }

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); }

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); }