0% found this document useful (0 votes)
46 views

10 - Sqlite

The document discusses SQLite databases in mobile application development. It covers database creation and insertion, querying databases, and using a database helper class. SQLite is an open-source lightweight database that stores data in a text file on a device.

Uploaded by

medawarsammy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views

10 - Sqlite

The document discusses SQLite databases in mobile application development. It covers database creation and insertion, querying databases, and using a database helper class. SQLite is an open-source lightweight database that stores data in a text file on a device.

Uploaded by

medawarsammy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 46

COSC 435 Mobile Application Development

Database & SQLite

Roaa SOLOH
solohrk@rhu.edu.lb
Fall 2022
Objectives

• Introduction to SQLiteDatabase
• Database Creation and Insertion
• Database Querying
• Database Helper Class
Introduction to SQLiteDatabase
What is a Database?

• Relational database: A method of structuring data as tables associated


to each other by shared attributes.
What is a Database?

• 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
Why Use a Database?

• fast: can search/filter a database very quickly compared to a


file
• big: scale well up to very large data sizes
• powerful: can search, filter, combine data from many sources
• safe: use of transactions for failure recovery
• 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
Some Database Software

• Oracle
• Microsoft
• SQLServer(powerful) / Access(simple)
• PostgreSQL
• powerful/complex free open-source DB system
• SQLite
• transportable, lightweight free open-source DB system
• MySQL
• simple free open-source database system
• many servers run “LAMP" (Linux, Apache, MySQL, and PHP)
• Wikipedia is run on PHP and MySQL
SQLiteDatabase

• SQLite is a open source SQL database that stores data to a text file on
a device.
• Android comes in with built in SQLite database implementation.
• SQLite supports all the relational database features.
• In order to access this database, you don't need to establish any kind
of connections for it like JDBC,ODBC etc.
• The package android.database.sqlite contains the classes to manage
your own databases
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)
• A declarative language: describes what data you are seeking,
instead of how to find it
• SELECT name FROM cities WHERE id = 17;
The Select Statement

SELECT column(s) FROM table WHERE


condition;
SELECT name, population FROM cities
WHERE country_code = “FSM";
searches a database and returns a set of results
column name(s) in SELECT filter which parts of rows are returned
SELECT DISTINCT removes duplicates
SELECT * keeps all columns
The Select Statement

SELECT column(s) FROM table WHERE


condition;
SELECT name, population FROM cities
WHERE country_code = "FSM";
WHERE clause filters out rows based on columns' data values
in large databases, WHERE clause is critical to reduce result
set size
table and column names are case- sensitive
WHERE Clauses

SELECT name, gnp FROM countries


WHERE gnp > 2000000;
SELECT * FROM cities
WHERE code = ‘USA' AND population >= 2000000;
SELECT code, name, population FROM countries
WHERE name LIKE 'United%';
WHERE Clauses
WHERE clause can use following operators:
• =, >, >=, <, <=
<> : not equal (some systems support !
=)
BETWEEN min AND max
LIKE pattern (put % on ends to search for prefix/suffix/substring)
IN (value, value, ..., value)
condition1 AND condition2 ;
condition1 OR condition2
ORDER BY

SELECT code, name, population


FROM countries
WHERE name LIKE 'United%'
ORDER BY population;
SELECT *
FROM countries
ORDER BY population DESC, gnp;
ORDER BY sorts in ascending (default) or descending order
can specify multiple orderings in decreasing order of significance
Related Tables

primary key:
column guaranteed to
be unique for each
row (ID)
Foreign key: key
referring to a primary
key
Join

SELECT column(s)
FROM table1 name1
JOIN table2 name2 ON condition(s)
... JOIN tableN nameN ON condition(s)
WHERE condition;

SELECT name, course_id, grade


FROM students s
JOIN grades g ON s.id = g.student_id
WHERE s.name = 'Bart';
Join

• JOIN combines related records from two or more tables


• ON clause specifies which records from each table are matched
• rows are often linked by their primary/ foreign key columns
Database Creation and Insertion
Database Creation

• To create a database, just need to call the method


openOrCreateDatabase
• SQLiteDatabase mydatabase =
openOrCreateDatabase( "your database name”,
MODE_PRIVATE,
null);
• Returns an instance of SQLite database.
Database Creation
•openOrCreateDatabase(name, mode, factory);
• name: The database name (unique in the application package).
• mode: Operating mode. Default is MODE_PRIVATE. Permissions
modes: MODE_WORLD_READABLE and
MODE_WORLD_WRITEABLE. Use
MODE_ENABLE_WRITE_AHEAD_LOGGING to enable write-
ahead logging by default.
• factory: An optional factory class that is called to instantiate a cursor
when query is called.
Opening Database

•openDatabase(String path, SQLiteDatabase.CursorFactory


factory, int flags)
•Opens the existing database in path with the appropriate flag mode.
The common flags mode are OPEN_READWRITE or
OPEN_READONLY
•openDatabase(String path, SQLiteDatabase.CursorFactory
factory, int flags, DatabaseErrorHandler errorHandler) Similar to
the above method but it also defines a handler to handle the errors of
databases
Insert Into a Database

•execSQL(String sql) or
•execSQL(String sql, Object[] bindArgs)
•These methods are used to update or modify already existing data in
database with or without using bind arguments.
•Example: mydatabase.execSQL("INSERT INTO MyTable
VALUES('admin','admin');");
ContentValues

• ContentValues can be optionally used as a level of abstraction for


statements like INSERT, UPDATE, REPLACE
• Meant to allow you to use cleaner Java syntax rather than raw SQL
syntax for some common operations.
ContentValues

Instead of using the following: db.execSQL("INSERT INTO tableName


("
+ columnName1 + ", " + columnName2
+ ") VALUES (" + value1 + ", " + value2 + ")");

Use:
ContentValues cvalues = new ContentValues(); cvalues.put("columnName1",
value1); cvalues.put("columnName2", value2);
...
db.insert("tableName", null, cvalues);
ContentValues
•db.insert (String table, String nullColumnHack, ContentValues values)
•table: the table to insert the row into
•nullColumnHack: may be null. SQL doesn't allow inserting an empty
row without naming at least one column name. This parameter provides the
name of a nullable column to explicitly insert a NULL into in the case
where values is empty.
•values: this map contains the initial column values for the row. The keys
should be the column names and the values the column values
•Returns the row ID of the newly inserted row, or -1 if an error occurred
Database Querying
Query Database

• To retrieve data from the database, can use the function rawQuery.
•public Cursor rawQuery (String sql, String[]
selectionArgs)
•sql: the SQL query. The SQL string must not be ; terminated
•selectionArgs: You may include ?s in where clause in the query,
which will be replaced by the values from selectionArgs. The values
will be bound as Strings.
Query Database

public Cursor rawQuery (String sql, String[]


selectionArgs)

Runs the provided SQL and returns a Cursor over the result set.

The Cursor object is positioned before the first entry and can be
moved forward to retrieve the data.
Cursor

Cursor resultSet = mydatbase.rawQuery ("Select * from


TutorialsPoint”, null);
resultSet.moveToFirst();
String username = resultSet.getString(1); String password =
resultSet.getString(2);
Cursor

• Other functions in the Cursor class:


• getColumnCount(): returns the total number of columns of
the table.
• getColumnIndex(String columnName): returns the
index number of a column by specifying the name of the
column
• getColumnName(int columnIndex): returns the name of
the column by specifying the index of the column
Cursor

Other functions in the Cursor class:


getColumnNames(): returns the array of all the column
names of the table.
getCount(): returns the total number of rows in the cursor
getPosition(): returns the current position of the
cursor in the table
isClosed(): returns true if the cursor is closed and returns
false otherwise
Cursor

Cursor cursor = db.rawQuery("SELECT *


FROM students”, null); cursor.moveToFirst();
do {
int id = cursor.getInt(
cursor.getColumnIndex("id")); String email = cursor.getString(
cursor.getColumnIndex("email"));
...
} while (cursor.moveToNext()); cursor.close();
Other Database Methods
db.beginTransaction()
db.endTransaction()
Begins a transaction in EXCLUSIVE mode.
The changes in the transaction will be rolled back if any transaction is
ended without being marked as clean (by calling
setTransactionSuccessful).
Otherwise they will be committed.
Transactions can be nested.
Other Database Methods
db.beginTransaction(); try {
...
db.setTransactionSuccessful();
} finally { db.endTransaction();
}
Other Database Methods
db.deleteDatabase(File file)
Deletes a database
Parameters
file: The database file path.
Returns: True if the database was successfully deleted.
Other Database Methods
•db.delete(String table, String whereClause, String[] whereArgs)
• Deletes rows in the database.
• table: the table to delete from
• whereClause: the optional WHERE clause to apply when deleting. If
null will delete all rows.
• whereArgs: Arguments for the whereClause if it includes ?s.
• Returns: the number of rows affected if a whereClause is passed in,
0 otherwise. To remove all rows and get a count pass, set "1" as the
whereClause.
Other Database Methods
•db.replace(String table, String nullColumnHack, ContentValues
initialValues)
• Replace a row in the database.
• table: the table in which to replace the row
• nullColumnHack: optional; may be null. If not null, it provides the
name of nullable column to explicitly insert a NULL into in case
initialValues is empty.
• initialValues: this map contains the initial column values for the
row.
• Returns: the row ID of the newly inserted row, or -1 if an error occurred
Other Database Methods
•db.update(String table, ContentValues values, String whereClause,
String[] whereArgs)
• update rows in the database.
• table: the table to update in
• values: a map from column names to new column values. null is a valid
value that will be translated to NULL.
• whereClause: optional WHERE clause to apply when updating. If null, all
rows are updated.
• whereArgs: value arguments if whereClause includes ?s
• Returns: the number of rows affected
Database Helper Class
SQLiteOpenHelper

• SQLiteOpenHelper: a helper class for managing all the


operations related to the database.
• It automatically manages opening the database if it exists,
creating it if it does not, and upgrading it as necessary.
• To use it:
• should create a subclass implementing SQLiteOpenHelper
• Override onCreate(SQLiteDatabase),
onUpgrade(SQLiteDatabase, int, int).
SQLiteOpenHelper
public class DBHelper
extends SQLiteOpenHelper { public DBHelper(Context context){
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {…}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {…}
}
SQLiteOpenHelper

•super(context, name, factory, version);


•context: to use to open or create the database
•name: of the database file
•factory: to use for creating cursor objects, or null for the default
•version: number of the database (starting at 1); if the database is
older, onUpgrade will be used to upgrade the database; if the
database is newer, onDowngrade will be used to downgrade the
database
SQLiteOpenHelper

•public void onCreate(SQLiteDatabase db)


• Called when the database is created for the first time.
• This is where the creation of tables and the initial population of
the tables should happen.
• Parameters:
• db: The database.
SQLiteOpenHelper
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
Called when the database needs to be upgraded.
Should use this method to drop tables, add tables, or do anything else it needs to upgrade to the new
schema version.
Executes within a transaction. If an exception is thrown, all changes are automatically rolled back.
Parameters
db: The database.
oldVersion: The old database version.
newVersion: The new database version.
onCreate()

private static final String TABLE_CREATE = "CREATE TABLE


mytable (" + KEY_WORD + " TEXT, " + KEY_DEFINITION + "
TEXT);";

@Override
public void onCreate(SQLiteDatabase db)
{ db.execSQL(TABLE_CREATE);
}
onUpdate()
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion != newVersion) {
// Simplest implementation is to drop all
// old tables and recreate them db.execSQL("DROP TABLE IF EXISTS "
+ TABLE_PASSWORDS); db.execSQL("DROP TABLE IF EXISTS "
+ TABLE_USERNAMES);
onCreate(db);
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy