relational database tables row column SQL



Similar documents
DIPLOMA IN WEBDEVELOPMENT

SQL - QUICK GUIDE. Allows users to access data in relational database management systems.

ANDROID APPS DEVELOPMENT FOR MOBILE GAME

CSI 2132 Lab 3. Outline 09/02/2012. More on SQL. Destroying and Altering Relations. Exercise: DROP TABLE ALTER TABLE SELECT

D61830GC30. MySQL for Developers. Summary. Introduction. Prerequisites. At Course completion After completing this course, students will be able to:

MySQL for Beginners Ed 3

IENG2004 Industrial Database and Systems Design. Microsoft Access I. What is Microsoft Access? Architecture of Microsoft Access

ICAB4136B Use structured query language to create database structures and manipulate data

SQL. by Steven Holzner, Ph.D. ALPHA. A member of Penguin Group (USA) Inc.

Financial Data Access with SQL, Excel & VBA

Database Administration with MySQL

Introduction to SQL and database objects

SQL Databases Course. by Applied Technology Research Center. This course provides training for MySQL, Oracle, SQL Server and PostgreSQL databases.

Web Programming Step by Step

A Brief Introduction to MySQL

Database: SQL, MySQL

HTSQL is a comprehensive navigational query language for relational databases.

Using Multiple Operations. Implementing Table Operations Using Structured Query Language (SQL)

A table is a collection of related data entries and it consists of columns and rows.

SQL. Short introduction

How To Create A Table In Sql (Ahem)

Zend Framework Database Access

SQL Injection. SQL Injection. CSCI 4971 Secure Software Principles. Rensselaer Polytechnic Institute. Spring

Introduction to Triggers using SQL

Relational Databases and SQLite

SAP Business Objects Business Intelligence platform Document Version: 4.1 Support Package Data Federation Administration Tool Guide

Beginning C# 5.0. Databases. Vidya Vrat Agarwal. Second Edition

Creating and Using Databases for Android Applications

1.204 Lecture 3. SQL: Basics, Joins SQL

Q&A for Zend Framework Database Access

Chapter 22 Database: SQL, MySQL,

Chapter 9 Joining Data from Multiple Tables. Oracle 10g: SQL

Oracle 10g PL/SQL Training

Overview of Databases On MacOS. Karl Kuehn Automation Engineer RethinkDB

Using SQL Server Management Studio

David Dye. Extract, Transform, Load

database abstraction layer database abstraction layers in PHP Lukas Smith BackendMedia

Talking to Databases: SQL for Designers

BCA. Database Management System

Intro to Databases. ACM Webmonkeys 2011

SQL Server for developers. murach's TRAINING & REFERENCE. Bryan Syverson. Mike Murach & Associates, Inc. Joel Murach

A basic create statement for a simple student table would look like the following.

Databasesystemer, forår 2005 IT Universitetet i København. Forelæsning 3: Business rules, constraints & triggers. 3. marts 2005

Developing Web Applications for Microsoft SQL Server Databases - What you need to know

3.GETTING STARTED WITH ORACLE8i

Chapter 9 Java and SQL. Wang Yang wyang@njnet.edu.cn

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff

Database Query 1: SQL Basics

SQL Simple Queries. Chapter 3.1 V3.0. Napier University Dr Gordon Russell

Advanced SQL. Jim Mason. Web solutions for iseries engineer, build, deploy, support, train

Introduction to SQL and SQL in R. LISA Short Courses Xinran Hu

Short notes on webpage programming languages

MOC 20461C: Querying Microsoft SQL Server. Course Overview

Web Development using PHP (WD_PHP) Duration 1.5 months

P_Id LastName FirstName Address City 1 Kumari Mounitha VPura Bangalore 2 Kumar Pranav Yelhanka Bangalore 3 Gubbi Sharan Hebbal Tumkur

Serious Threat. Targets for Attack. Characterization of Attack. SQL Injection 4/9/2010 COMP On August 17, 2009, the United States Justice

SQL Injection. Sajjad Pourali CERT of Ferdowsi University of Mashhad

Oracle Database: SQL and PL/SQL Fundamentals NEW

Information Technology NVEQ Level 2 Class X IT207-NQ2012-Database Development (Basic) Student s Handbook

USING MYWEBSQL FIGURE 1: FIRST AUTHENTICATION LAYER (ENTER YOUR REGULAR SIMMONS USERNAME AND PASSWORD)

Facebook Twitter YouTube Google Plus Website

Oracle Database: SQL and PL/SQL Fundamentals

Structured Query Language. Telemark University College Department of Electrical Engineering, Information Technology and Cybernetics

Relational Databases. Christopher Simpkins

Triggers & Packages. {INSERT [OR] UPDATE [OR] DELETE}: This specifies the DML operation.

Geodatabase Programming with SQL

Certified PHP/MySQL Web Developer Course

What is a database? COSC 304 Introduction to Database Systems. Database Introduction. Example Problem. Databases in the Real-World

Database Systems. Lecture 1: Introduction

Database Management System Choices. Introduction To Database Systems CSE 373 Spring 2013

Database Programming with PL/SQL: Learning Objectives

ITG Software Engineering

How, What, and Where of Data Warehouses for MySQL

Android Persistency: SQL Databases

White Paper. Blindfolded SQL Injection

Demystified CONTENTS Acknowledgments xvii Introduction xix CHAPTER 1 Database Fundamentals CHAPTER 2 Exploring Relational Database Components

The Relational Model. Why Study the Relational Model? Relational Database: Definitions

Connecting to a Database Using PHP. Prof. Jim Whitehead CMPS 183, Spring 2006 May 15, 2006

Managing Objects with Data Dictionary Views. Copyright 2006, Oracle. All rights reserved.

Adam Rauch Partner, LabKey Software Extending LabKey Server Part 1: Retrieving and Presenting Data

A SQL Injection : Internal Investigation of Injection, Detection and Prevention of SQL Injection Attacks

Oracle Database 12c: Introduction to SQL Ed 1.1

1.264 Lecture 11. SQL: Basics, SELECT. Please start SQL Server before each class

DBMS / Business Intelligence, SQL Server

Instant SQL Programming

G563 Quantitative Paleontology. SQL databases. An introduction. Department of Geological Sciences Indiana University. (c) 2012, P.

INFORMATION BROCHURE Certificate Course in Web Design Using PHP/MySQL

WI005 - Offline data sync con SQLite in Universal Windows Platform

Lab # 5. Retreiving Data from Multiple Tables. Eng. Alaa O Shama

A Comparison of Database Query Languages: SQL, SPARQL, CQL, DMX

B.1 Database Design and Definition

SQL Server Database Coding Standards and Guidelines

Querying Microsoft SQL Server

Oracle Database: SQL and PL/SQL Fundamentals

Introduction to Database. Systems HANS- PETTER HALVORSEN,

Transcription:

SQLite in Android 1

What is a database? relational database: A method of structuring data as tables associated to each other by shared attributes. a table row corresponds to a unit of data called a record; a column corresponds to an attribute of that record relational databases typically use Structured Query Language (SQL) to define, manage, and search data 2

Why use a database? powerful: can search, filter, combine data from many sources fast: can search/filter a database very quickly compared to a file big: scale well up to very large data sizes safe: built-in mechanisms for failure recovery (transactions) multi-user: concurrency features let many users view/edit data at same time abstract: layer of abstraction between stored data and app(s) common syntax: database programs use same SQL commands 3

Relational database A database is a set of tables Each table has a primary key a column with unique values to identify a row Tables can be related via foreign keys. 4

Some database software Oracle Microsoft SQLServer(powerful) Access(simple) PostgreSQL powerful/complex free open-source database system SQLite transportable, lightweight free open-source database system MySQL simple free open-source database system many servers run LAMP (Linux,Apache,MySQL,andPHP) Wikipedia is run on PHP and MySQL 5

Android includes SQLite SQLite is a library, runs in the app s process 6

Android Media Manager (Media Content Provider) The Media provider contains meta data for all available media on both internal and external storage devices. SQLite: metadata: file location size artist albums raw files playlists 7

The main table in Media: files A single table to represent all types of media files: Each row can be an image, audio, video, or playlist _id _data _size title 1 a.jpg 10000 a 2 b.bmp 20000 b 3 c.mp3 320000 c 4 d.avi 12312000 d http://androidxref.com/4.4.3_r1.1/xref/packages/providers/ MediaProvider/src/com/android/providers/media/ MediaProvider.java#1335 8

Other tables in Media thumbnails, artists, albums, audio_playlists_map (stores members of a playlist) 9

SQL Structured Query Language (SQL): a language for searching and updating a database a standard syntax that is used by all database software (with minor incompatibilities) generally case-insensitive a declarative language: describes what data you are seeking, not exactly how to find it 10

Basic SQL operations SELECT INSERT UPDATE DELETE 11

SELECT SELECT <list of columns> FROM <table> WHERE <where clause> [ORDER BY <column> [ASC or DESC]] [LIMIT <number>]; e.g., SELECT * FROM files WHERE _id=3; _id _data _size title 1 a.jpg 10000 a 2 b.bmp 20000 b 3 c.mp3 320000 c 4 d.avi 12312000 d 12

SELECT SELECT <list of columns> FROM <table> WHERE <where clause> [ORDER BY <column> [ASC or DESC]] [LIMIT <number>]; SELECT _id, _data FROM files SELECT * FROM files; (* means all columns) ORDER BY: sort the result by a column LIMIT: only get the first n rows in the result 13

INSERT INSERT INTO <table> (<list of columns>) VALUES (<list of values>); e.g., INSERT INTO files (data, size, title) VALUES ( image0.jpg, 102400, image0 ); _id _data _size title 1 a.jpg 10000 a 2 b.bmp 20000 b 3 c.mp3 320000 c 4 d.avi 12312000 d 5 image0.jpg 102400 image0 14

UPDATE UPDATE <table> SET <column1> = <value1>, <column2> = <value2>, <columnn> = <valuen> WHERE <where clause>; 15

UPDATE e.g., UPDATE files SET title= profile WHERE _id=5; _id _data _size title 1 a.jpg 10000 a 2 b.bmp 20000 b 3 c.mp3 320000 c 4 d.avi 12312000 d 5 image0.jpg 102400 profile 16

DELETE DELETE FROM <table> WHERE <where clause>; e.g., DELETE FROM files WHERE _id=4; _id _data _size title 1 a.jpg 10000 a 2 b.bmp 20000 b 3 c.mp3 320000 c 4 d.avi 12312000 d 5 image0.jpg 102400 profile 17

Related data across tables thumbnail _id _data image_id width file _id _data _size titile 18

Related data across tables thumbnail _id _data image_id? width 19

Foreign keys If thumbnails.image_id is declared to be a foreign key of files._id, SQLite will enforce Referential Integrity: When a row in files is removed or its _id is changed, SQLite can set the affected foreign keys in thumbnails to NULL, or remove the affected rows, etc. 20

Foreign keys files table _id _data _size title 1 a.jpg 10000 a 2 b.bmp 20000 b 3 c.mp3 320000 c 5 image0.jpg 102400 profile thumbnails table _id _data image_id width 1 1.thumb 1 300 3 5.thumb 5 600 21

ON DELETE CASCADE files table _id _data _size title 1 a.jpg 10000 a 2 b.bmp 20000 b 3 c.mp3 320000 c 5 image0.jpg 102400 profile thumbnails table _id _data image_id width 1 1.thumb 1 300 3 5.thumb 5 600 22

ON DELETE SET NULL files table _id _data _size title 1 a.jpg 10000 a 2 b.bmp 20000 b 3 c.mp3 320000 c 5 image0.jpg 102400 profile thumbnails table _id _data image_id width 1 1.thumb NULL 1 300 3 5.thumb 5 600 23

Join query multiple related tables Inner join Outer join If multiple tables have the same column name, use <table>.<col> to distinguish them 24

Inner Join Inner join (JOIN) only returns rows matching the condition SELECT FROM files JOIN thumbnails ON files._id=thumbnails.image_id WHERE Equivalent to SELECT FROM files, thumbnails WHERe files._id=thumbnails.image_id AND ( ) 25

files Inner Join _id _data _size title 1 a.jpg 10000 a 2 b.bmp 20000 b 5 image0.jpg 102400 profile thumbnails _id _data image_id width 1 1.thumb 1 300 3 5.thumb 5 600 JOIN ON files._id=thumbnails.image_id files._id title thumbnails._id width 1 a 1 300 5 profile 3 600 26

Outer Join Left outer join (LEFT [OUTER] JOIN) returns all rows in the left table, fill NULL to the right table if no matching rows. Right outer join returns all rows in the right table, fill NULL to the left table if no matching rows. (not supported by SQLite) Full outer join records from both sides are included, fill NULL to the other table if no match. (not supported by SQLite) 27

Left Outer Join Left outer join (LEFT [OUTER] JOIN) returns all rows in the left table, fill NULL to the right table if no matching rows. SELECT FROM files LEFT OUTER JOIN thumbnails ON files._id=thumbnails.image_id WHERE 28

files Left Outer Join _id _data _size title 1 a.jpg 10000 a 2 b.bmp 20000 b 5 image0.jpg 102400 profile thumbnails _id _data image_id width 1 1.thumb 1 300 3 5.thumb 5 600 JOIN ON files._id=thumbnails.image_id files._id title thumbnails._id width 1 a 1 300 2 b NULL NULL 5 profile 3 600 29

Views A view is a virtual table based on other tables or views CREATE VIEW <view name> AS SELECT.; _id _data _size title type 1 a.jpg 10000 a image 2 b.bmp 20000 b image 3 c.mp3 320000 c audio 5 image0.jpg 102400 profile image select only images _id _data _size title 1 a.jpg 10000 a 2 b.bmp 20000 b 5 image0.jpg 102400 profile 30

Views in Media Provider <view> <table> audio video images audio_meta artists albums files 31

Views in Media Provider CREATE VIEW audio_meta AS SELECT _id, <audio-related columns>, FROM files WHERE media_type =<MEDIA_TYPE_AUDIO>; CREATE VIEW IF NOT EXISTS audio AS SELECT * FROM audio_meta LEFT OUTER JOIN artists ON audio_meta.artist_id=artists.artist_id LEFT OUTER JOIN albums ON audio_meta.album_id=albums.album_id; 32

Android SQLiteDatabase A class to use SQLite. SQLiteDatabase db = openorcreatedatabase( "name", MODE_PRIVATE, null); db.execsql("sql query"); 33

Android SQLiteDatabase It helps you to generate SQL statements. query (SELECT), delete, insert, update db.begintransaction(), db.endtransaction() db.delete("table", "whereclause",args) db.deletedatabase(file) db.insert("table", null, values) db.query(...) db.rawquery("sqlquery", args) db.replace("table", null, values) db.update("table", values, "whereclause", args) 34

Avoid using user-provided input as part of a raw query SQL injection: statement = "SELECT * FROM users WHERE name =\'" + username + "\';" If the user provides username = " ' OR '1'='1 " Statement becomes: SELECT * FROM users WHERE name = OR 1 = 1 ; always true. 35

Avoid using user-provided input as part of a raw query Use ContentValues and arguments for user-provided input. 36

ContentValues ContentValues cvalues = new ContentValues(); cvalues.put("columnname1", value1); cvalues.put("columnname2", value2);... db.insert("tablename", null, cvalues); ContentValues can be optionally used as a level of abstraction for statements like INSERT, UPDATE, REPLACE 37

Compare to raw statements Contrast with: db.execsql("insert INTO tablename (" + columnname1 + ", " + columnname2 + ") VALUES (" + value1 + ", " + value2 + ")"); ContentValues allows you to use cleaner Java syntax rather than raw SQL syntax for some common operations. 38

Arguments query(string table, String[] columns, String selection, String[] selectionargs, String groupby, String having, String orderby) selection: a where clause that can contain? type=? and date=? selectionargs: [ image, 10/1/2016 ] 39

Cursor: result of a query Cursor lets you iterate through row results one at a time Cursor cursor = db.rawquery("select * FROM students"); cursor.movetofirst(); do { int id = cursor.getint(cursor.getcolumnindex("id")); String email = cursor.getstring( cursor.getcolumnindex("email"));... } while (cursor.movetonext()); cursor.close(); 40