Download presentation
Presentation is loading. Please wait.
1
Programming with Android:
Data management Dr. ASM M Rahaman
2
Managing Data Preferences: Key/Value pairs of data
Direct File I/O: Read/write files onboard or on SD cards. Remember to request permission for writing, for instance, on SD card Database Tables: SQL Lite Application Direct Access: Read only access from res assets/raw directories Increase functionality: Content Providers: expose data to other applications Services: background processes that run detached from any view
3
SQLite General purpose solution Standard SQL syntax
– Lightweight database based on SQL Standard SQL syntax SELECT name FROM table WHERE name = “Luca” Android gives a standard interface to SQL tables of other apps For application tables no content providers are needed
4
Better to use constants like
A database to store information Useful for structured informations Create a DBHelper which extends SQLiteOpenHelper Fill it with methods for managing the database Better to use constants like TABLE_GRADES COLUMN_NAME • ….
5
Our database will look like this:
SQLite: example Our database will look like this: grade table: id: integer, primary key, auto increment firstName: text, not null lastName: text, not null class: text, not null grade: integer, not null
6
SQLite: better to use constants
Useful for query definition Our constants? private static final String DB_NAME = “grades.db”;; private static final int DB_VERSION = 1;; public static final String TABLE_GRADES = “grades”;; public static final String COL_ID = “id”;; public static final String COL_FIRSTNAME = “firstName”;; public static final String COL_LASTNAME = “lastName”;; public static final String COL_CLASS = “class”;; public static final String COL_GRADE = “grade”;;
7
Constructor: call the superconstructor
SQLite: creation code Constructor: call the superconstructor Public mySQLiteHelper(Context context) { super(context, DB_NAME, null, DB_VERSION);; } onCreate(SQLiteDatabase db): create the tables String sql_grade = “create table “ + TABLE_GRADES + “( “ + COL_ID + “ integer primary key autoincrement, “ + COL_FIRSTNAME + “ text not null, “ + COL_LASTNAME + “ text not null, “ + COL_CLASS + “ text not null, “ + COL_GRADE + “ text not null “);;”;; db.execSQL(sql_grade);;
8
Create a public method, like insertDb(…)
SQLite: insert code Create a public method, like insertDb(…) mySQLiteHelper sql = new mySQLiteHelper(InsertActivity.this);; SQLiteDatabase db = mySQLiteHelper.getWritableDatabase();; ContentValues cv = new ContentValues();; cv.put(mySQLiteHelper.COL_FIRSTNAME, firstName);; cv.put(mySQLiteHelper.COL_LASTNAME, lastName);; cv.put(mySQLiteHelper.COL_CLASS, className);; cv.put(mySQLiteHelper.COL_GRADE, grade);; long id = db.insert(mySQLiteHelper.TABLE_GRADES, null, values);;
9
Create a public method, like deleteDb(…)
SQLite: delete code Create a public method, like deleteDb(…) The delete method returns the number of rows affected Example: db.delete(mySQLiteHelper.TABLE_GRADES, “id = ?”, new String[] {Integer.toString(id_to_delete)});;
10
Create a public method, like updateDb(…)
SQLite: update code Create a public method, like updateDb(…) ContentValues cv = new ContentValues();; values.put(mySQLiteHelper.FIRSTNAME, firstName);; values.put(mySQLiteHelper.LASTNAME, lastName);; db.update(mySQLiteHelper.TABLE_GRADES, values, “id = ?”, new {Integer.toString(id_to_update));; String[]
11
Create a public method, like getFromDb(…)
SQLite: search code Create a public method, like getFromDb(…) Cursor gradeCursor = db.query(mySQLiteHelper.TABLE_GRADES, new String[]{mySQLiteHelper.COL_GRADE}, mySQLiteHelper.COL_ID + “ = “ + id_to_search_for, null, null, null, null);;
12
SQL Data Definition Language (DDL) Data Manipulation Language (DML)
Create/alter/delete tables and their attributes Following lectures... Data Manipulation Language (DML) Query one or more tables – discussed next ! Insert/delete/modify tuples in tables
13
PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks
Tables in SQL Table name Attribute names Product PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi Tuples or rows
14
Tables Explained The schema of a table is the table name and its attributes: Product(PName, Price, Category, Manfacturer) A key is an attribute whose values are unique; we underline a key
15
Data Types in SQL Atomic types: Characters: CHAR(20), VARCHAR(50)
Numbers: INT, BIGINT, SMALLINT, FLOAT Others: MONEY, DATETIME, …
16
Data Definition Language
The SQL data-definition language (DDL) allows the specification of information about relations, including: The schema for each relation. The domain of values associated with each attribute. Integrity constraints And as we will see later, also other information such as The set of indices to be maintained for each relations. Security and authorization information for each relation. The physical storage structure of each relation on disk.
17
Domain Types in SQL char(n). Fixed length character string, with user-specified length n. varchar(n). Variable length character strings, with user-specified maximum length n. int. Integer (a finite subset of the integers that is machine-dependent). smallint. Small integer (a machine-dependent subset of the integer domain type). numeric(p,d). Fixed point number, with user-specified precision of p digits, with d digits to the right of decimal point. (ex., numeric(3,1), allows 44.5 to be stores exactly, but not or 0.32) real, double precision. Floating point and double-precision floating point numbers, with machine-dependent precision. float(n). Floating point number, with user-specified precision of at least n digits. More are covered in Chapter 4.
18
Create Table Construct
An SQL relation is defined using the create table command: create table r (A1 D1, A2 D2, ..., An Dn, (integrity-constraint1), , (integrity-constraintk)) r is the name of the relation each Ai is an attribute name in the schema of relation r Di is the data type of values in the domain of attribute Ai Example: create table instructor ( ID char(5), name varchar(20), dept_name varchar(20), salary numeric(8,2))
19
Integrity Constraints in Create Table
not null primary key (A1, ..., An ) foreign key (Am, ..., An ) references r Example: create table instructor ( ID char(5), name varchar(20) not null, dept_name varchar(20), salary numeric(8,2), primary key (ID), foreign key (dept_name) references department); primary key declaration on an attribute automatically ensures not null
20
And a Few More Relation Definitions
create table student ( ID varchar(5), name varchar(20) not null, dept_name varchar(20), tot_cred numeric(3,0), primary key (ID), foreign key (dept_name) references department); create table takes ( ID varchar(5), course_id varchar(8), sec_id varchar(8), semester varchar(6), year numeric(4,0), grade varchar(2), primary key (ID, course_id, sec_id, semester, year) , foreign key (ID) references student, foreign key (course_id, sec_id, semester, year) references section); Note: sec_id can be dropped from primary key above, to ensure a student cannot be registered for two sections of the same course in the same semester
21
primary key (course_id),
And more still create table course ( course_id varchar(8), title varchar(50), dept_name varchar(20), credits numeric(2,0), primary key (course_id), foreign key (dept_name) references department);
22
Basic form: (plus many many more bells and whistles)
SQL Query Basic form: (plus many many more bells and whistles) SELECT <attributes> FROM <one or more relations> WHERE <conditions>
23
Simple SQL Query Product PName Price Category Manufacturer Gizmo
$19.99 Gadgets GizmoWorks Powergizmo $29.99 SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi SELECT * FROM Product WHERE category=‘Gadgets’ PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 “selection”
24
Simple SQL Query Product PName Price Category Manufacturer Gizmo
$19.99 Gadgets GizmoWorks Powergizmo $29.99 SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi SELECT PName, Price, Manufacturer FROM Product WHERE Price > 100 PName Price Manufacturer SingleTouch $149.99 Canon MultiTouch $203.99 Hitachi “selection” and “projection”
25
Notation Product(PName, Price, Category, Manfacturer)
Input Schema Product(PName, Price, Category, Manfacturer) SELECT PName, Price, Manufacturer FROM Product WHERE Price > 100 Answer(PName, Price, Manfacturer) Output Schema
26
Details Case insensitive: Constants: Same: SELECT Select select
Same: Product product Different: ‘Seattle’ ‘seattle’ Constants: ‘abc’ - yes “abc” - no
27
SELECT * FROM Products WHERE PName LIKE ‘%gizmo%’
The LIKE operator SELECT * FROM Products WHERE PName LIKE ‘%gizmo%’ s LIKE p: pattern matching on strings p may contain two special symbols: % = any sequence of characters _ = any single character
28
Eliminating Duplicates
Category Gadgets Photography Household SELECT DISTINCT category FROM Product Compare to: Category Gadgets Photography Household SELECT category FROM Product
29
Ties are broken by the second attribute on the ORDER BY list, etc.
Ordering the Results SELECT pname, price, manufacturer FROM Product WHERE category=‘gizmo’ AND price > 50 ORDER BY price, pname Ties are broken by the second attribute on the ORDER BY list, etc. Ordering is ascending, unless you specify the DESC keyword.
30
? ? ? PName Price Category Manufacturer Gizmo $19.99 Gadgets
GizmoWorks Powergizmo $29.99 SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi SELECT DISTINCT category FROM Product ORDER BY category ? ? SELECT Category FROM Product ORDER BY PName ? SELECT DISTINCT category FROM Product ORDER BY PName
31
Keys and Foreign Keys Company Product CName StockPrice Country
GizmoWorks 25 USA Canon 65 Japan Hitachi 15 Key Product PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi Foreign key
32
Join between Product and Company
Joins Product (pname, price, category, manufacturer) Company (cname, stockPrice, country) Find all products under $200 manufactured in Japan; return their names and prices. Join between Product and Company SELECT PName, Price FROM Product, Company WHERE Manufacturer=CName AND Country=‘Japan’ AND Price <= 200
33
Joins Product Company PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi Cname StockPrice Country GizmoWorks 25 USA Canon 65 Japan Hitachi 15 SELECT PName, Price FROM Product, Company WHERE Manufacturer=CName AND Country=‘Japan’ AND Price <= 200 PName Price SingleTouch $149.99
34
More Joins Product (pname, price, category, manufacturer)
Company (cname, stockPrice, country) Find all Chinese companies that manufacture products both in the ‘electronic’ and ‘toy’ categories SELECT cname FROM WHERE
35
A Subtlety about Joins Product (pname, price, category, manufacturer)
Company (cname, stockPrice, country) Find all countries that manufacture some product in the ‘Gadgets’ category. SELECT Country FROM Product, Company WHERE Manufacturer=CName AND Category=‘Gadgets’ Unexpected duplicates
36
A Subtlety about Joins What is the problem ? What’s the solution ?
Product Company Name Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi Cname StockPrice Country GizmoWorks 25 USA Canon 65 Japan Hitachi 15 SELECT Country FROM Product, Company WHERE Manufacturer=CName AND Category=‘Gadgets’ What is the problem ? What’s the solution ? Country ??
37
Same query, except that we consider only products that had
HAVING Clause Same query, except that we consider only products that had at least 100 buyers. SELECT product, Sum(price * quantity) FROM Purchase WHERE date > ‘10/1/2005’ GROUP BY product HAVING Sum(quantity) > 30 HAVING clause contains conditions on aggregates.
38
Product Purchase Name Category Gizmo gadget Camera Photo OneClick ProdName Store Gizmo Wiz Camera Ritz Name Store Gizmo Wiz Camera Ritz OneClick NULL
39
Modifying the Database
Three kinds of modifications Insertions Deletions Updates Sometimes they are all called “updates”
40
Example: Insert a new purchase to the database:
Insertions General form: INSERT INTO R(A1,…., An) VALUES (v1,…., vn) Example: Insert a new purchase to the database: INSERT INTO Purchase(buyer, seller, product, store) VALUES (‘Joe’, ‘Fred’, ‘wakeup-clock-espresso-machine’, ‘The Sharper Image’) Missing attribute NULL. May drop attribute names if give them in order.
41
Insertions INSERT INTO PRODUCT(name) SELECT DISTINCT Purchase.product FROM Purchase WHERE Purchase.date > “10/26/01” The query replaces the VALUES keyword. Here we insert many tuples into PRODUCT
42
prodName is foreign key in Product.name
Insertion: an Example Product(name, listPrice, category) Purchase(prodName, buyerName, price) prodName is foreign key in Product.name Suppose database got corrupted and we need to fix it: Purchase Product prodName buyerName price camera John 200 gizmo Smith 80 225 name listPrice category gizmo 100 gadgets Task: insert in Product all prodNames from Purchase
43
INSERT INTO Product(name) SELECT DISTINCT prodName FROM Purchase
Insertion: an Example INSERT INTO Product(name) SELECT DISTINCT prodName FROM Purchase WHERE prodName NOT IN (SELECT name FROM Product) name listPrice category gizmo 100 Gadgets camera -
44
INSERT INTO Product(name, listPrice) SELECT DISTINCT prodName, price
Insertion: an Example INSERT INTO Product(name, listPrice) SELECT DISTINCT prodName, price FROM Purchase WHERE prodName NOT IN (SELECT name FROM Product) name listPrice category gizmo 100 Gadgets camera 200 - camera ?? 225 ?? Depends on the implementation
45
WHERE seller = ‘Joe’ AND product = ‘Brooklyn Bridge’
Deletions Example: DELETE FROM PURCHASE WHERE seller = ‘Joe’ AND product = ‘Brooklyn Bridge’ Factoid about SQL: there is no way to delete only a single occurrence of a tuple that appears twice in a relation.
46
Updates Example: UPDATE PRODUCT SET price = price/2 WHERE Product.name IN (SELECT product FROM Purchase WHERE Date =‘Oct, 25, 1999’);
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.