SlideShare a Scribd company logo
Database in Android
Android Data Managenent using
SQL Lite
What is SQL lite..?
●
●
SQLite is a relational database management system
contained in a C programming library. In contrast to many
other database management systems, SQLite is not a
client–server database engine. Rather, it is embedded into
the end program.
SQLite is ACID-compliant and implements most of the SQL
standard, using a dynamically and weakly typed SQL
syntax
Origins of sql lite
●
●
D. Richard Hipp designed SQLite in the spring of 2000
while working for General Dynamics on contract with the
United States Navy. Hipp was designing software used
aboard guided missile destroyers, which were originally
based on HP-UX with an IBM Informix database back-end.
SQLite began as a Tcl extension.
The design goals of SQLite were to allow the program to
be operated without installing a database management
system or requiring a database administrator.
Why sql lite
●
●
●
●
●
No server is required
Object(document) based design
Reqire Zero(less) Configration
One machine database
Multitasking database
Using SQL databases in Android
Android (as well as iPhone OS) uses an embedded standalone
program called sqlite3 which can be used to
create a database,
indices,
views,
Insert rows,
change rows,
define SQL tables,
queries,
triggers
delete rows,
run queries and
administer a SQLite database file.
How to create a SQLitedatabase
Open the database according to the flags OPEN_READWRITE OPEN_READONLY
CREATE_IF_NECESSARY . Sets the locale of the database to the thesystem's current
locale.
public static SQLiteDatabase.openDatabase(
Stringpath, SQLiteDatabase.CursorFactory factory, int flags )
Parameters
path to database file to open and/or create
factory an optional factory class that is called to instantiate a cursor when
query is called, or null for default
flags to control database access mode
Returns the newly opened database
Throws SQLiteException if the database cannot be opened
How to create a SQLitedatabase
SQLiteDatabase db=this.openOrCreateDatabase
( "myfriendsDB",MODE_PRIVATE, null);
where the assumed prefix for the database stored in the devices ram is:
"/data/data/<CURRENT_namespace>/databases/". For instance if this app is
created in a namespace called “cis493.sql1”, the full name of the newly created
database will be: “/data/data/cis493.sql1/databases/myfriendsDB”.
MODEcould be: MODE_PRIVATE, MODE_WORLD_READABLE, and
MODE_WORLD_WRITEABLE. Meaningful for apps consisting of multiples
activities
no Method & Description
1 openDatabase(String path, SQLiteDatabase.CursorFactory factory, int
flags, DatabaseErrorHandler errorHandler)
This method only opens the existing database with the appropriate
flag mode. The common flags mode could be OPEN_READWRITE
OPEN_READONLY
2 openDatabase(String path, SQLiteDatabase.CursorFactory factory, int
flags)
It is similar to the above method as it also opens the existing database but it
does not define any handler to handle the errors of databases
no Method & Description
3 openOrCreateDatabase(String path,
SQLiteDatabase.CursorFactory factory)
It not only opens but create the database if it not exists. This method
is equivalent to openDatabase method
4 openOrCreateDatabase(File
file,SQLiteDatabase.CursorFactory factory)
It is similar to the above method as it also opens the existing database but it
does not define any handler to handle the errors of databases
Executing SQL commands on the
Database
Action queries and Retrieval queries represent the most common operations
against the database
Retrieval query : typically a SQL-Select command in which a table holding a
number of fields and rows is produced as an answer to a data request.
Action query : usually performs maintenance and administrative tasks such as
manipulating tables, users, environment, etc.
Transection Processing
The transaction is defined between the methods: beginTransaction and
endTransaction. You need to issue the setTransactionSuccessful() call
to commit any changes. the absence of it provokes an implicit rollback;
consequently the database is reset to the state previous to the beginning
of the transaction
Creating a Table
We will use the execSQL(…)method to manipulate SQL action queries.
db.execSQL("create table tblAMIGO(" + " recIDinteger PRIMARY KEY autoincrement,
" + " name text,
"+ " phone text );
" );
Create table
The database data types are very simple, for instance we will use: text,varchar,
integer, float, numeric, date, time, timestamp, blob, boolean, and so on.
1.In general, any well-formed SQL action command (insert, delete, update,
create, drop, alter, etc.) could be framed inside an execSQL(…) method.
2.You should make the call to execSQLinside of a try-catch-finally block. Be
aware of potential SQLiteExceptionsituations thrown by the method.
Retrieval queries
Retrieval queries are SQL-select statements.
Android offers two mechanisms for phrasing SQL-select statements:
1.Raw queries take for input a syntactically correct SQL-select statement. The
select query could be as complex as needed and involve any number of tables
(remember that outer joins are not supported).
2.Simple queries are compact parametized select statements that operate on a
single table (for developers who prefer not to use SQL).
RawQuery
Cursor c1 = db.rawQuery(
"select count(*) as Total from Student",
null);
The rawQuery contains a select-statement that counts the rows in the table
Student.
2.The result of this count is held in a table having only one row and one column.
The column is called “Total”.
3.The cursor c1will be used to traverse the rows (one!) of the resulting table.
4.Fetching a row using cursor c1 requires advancing to the next record in the
answer set.
5.Later the (singleton) field total must be bound to a local Java variable
Cursors
Android cursor s are used to gain (random) access to tables produced by SQL
select statements.
Cursors primarily provide one row-at-the-time operations on a table. Cursors
include several types of operator
1.Positional awareness operators (isFirst(), isLast(), isBeforeFirst(),
isAfterLast()),
2.Record Navigation (moveToFirst(), moveToLast(), moveToNext(),
moveToPrevious(), move(n))
3. Field extraction (getInt, getString, getFloat, getBlob, getDate, etc.)
4.Schema inspection (getColumnName, getColumnNames, getColumnIndex,
getColumnCount, getCount)
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, coding the database class, building and executing  queries
Cursors provide READ_ONLYaccess to records.
2.Early versions of the Android SDK included cursor commands to
sequentially modify records. Those operators have been deprecated in
Release 1.0.
3.Methods such as cursor.updateInt(...)and cursor.deleteRow(...)are not valid
anymore.
4.Instead use an action SQL command in an execSQL(...)method .
ParametizedRawQuery
String mySQL= "select count(*) as Total "
+ " from Student"
+ " where recID> ?"
+ " and name = ?";
String [] args= {"114337", "Dipak"};
Cursor c1 = db.rawQuery (mySQL, args);
Simple Querie
Simple queries can only retrieve data from a single table.(non-joining ) it is an
template
The method’s signature has a fixed sequence of seven arguments representing:
1.the table name,
2.the columns to be retrieved,
3.the search condition (where-clause),
4.arguments for the where-clause,
5.the group-by clause,
6.having-clause, and
7.the order-by clause.
example
SQL Action Queries
insert into student values ( ‘Macarena’, ‘555-1234’);
update student set name = ‘Maria Macarena’ where phone = ‘555-1234’;
delete from where phone = ‘555-1234’;
create table Temp ( column1 int, column2 text, column3 date );
drop table Temp;
Action queries
Insert Operator
public long insert (String table, String nullColumnHack, ContentValues values)
Insertion
●
●
execSQL(String sql, Object[ ] bindArgs)
This method not only insert data , but also used to update
or modify already existing data in database using bind
arguments
update Operator
public int update ( String table,
ContentValues values,
String whereClause, String[ ] whereArgs)
Parameters
table :
values :
the table to update in
a map <name,value> from column names to new column values.
null is a valid value that will be translated to NULL.
whereClause : the optional WHERE clause to apply when updating.
Passing null will update all rows.
Returns : the number of rows affected
delete Operator
public int delete( String table, String whereClause , String[ ] whereArgs)
Parameters
table the table to delete from
whereClause the optional WHERE clause to apply when deleting. Passing
null will delete all rows.
Returns the number of rows affected if a whereClauseis passed in,
0 otherwise.
To remove all rows and get a count pass "1" as the whereClause

More Related Content

Similar to Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, coding the database class, building and executing queries (20)

PPTX
Unit - IV.pptx
VaishnaviGaikwad67
 
PPTX
Unit - IV (1).pptx
VaishnaviGaikwad67
 
PPTX
Session #4 b content providers
Vitali Pekelis
 
PPTX
09.1. Android - Local Database (Sqlite)
Oum Saokosal
 
PDF
Sql queries - Basics
Purvik Rana
 
PPT
SQLITE Android
Sourabh Sahu
 
PPTX
Android Database
Rashad Aliyev
 
PDF
Android App Development 05 : Saving Data
Anuchit Chalothorn
 
PPT
Sq lite database
AYESHA JAVED
 
PDF
Android Level 2
DevMix
 
DOCX
Android database tutorial
info_zybotech
 
PPTX
Session #5 content providers
Vitali Pekelis
 
PPTX
Data Handning with Sqlite for Android
Jakir Hossain
 
PPTX
MAD UNIT 5 FINAL.pptx
Siva Krishna Prasad
 
PPTX
Android Training (Storing data using SQLite)
Khaled Anaqwa
 
PDF
Cursor & Content Value.pdf
uttamrao7
 
PPTX
Create an android app for database creation using.pptx
vishal choudhary
 
PPT
Android SQLite database oriented application development
Kongu Engineering College, Perundurai, Erode
 
DOCX
Sq lite
Revuru Bharadwaja
 
PPTX
Databases in Android Application
Mark Lester Navarro
 
Unit - IV.pptx
VaishnaviGaikwad67
 
Unit - IV (1).pptx
VaishnaviGaikwad67
 
Session #4 b content providers
Vitali Pekelis
 
09.1. Android - Local Database (Sqlite)
Oum Saokosal
 
Sql queries - Basics
Purvik Rana
 
SQLITE Android
Sourabh Sahu
 
Android Database
Rashad Aliyev
 
Android App Development 05 : Saving Data
Anuchit Chalothorn
 
Sq lite database
AYESHA JAVED
 
Android Level 2
DevMix
 
Android database tutorial
info_zybotech
 
Session #5 content providers
Vitali Pekelis
 
Data Handning with Sqlite for Android
Jakir Hossain
 
MAD UNIT 5 FINAL.pptx
Siva Krishna Prasad
 
Android Training (Storing data using SQLite)
Khaled Anaqwa
 
Cursor & Content Value.pdf
uttamrao7
 
Create an android app for database creation using.pptx
vishal choudhary
 
Android SQLite database oriented application development
Kongu Engineering College, Perundurai, Erode
 
Databases in Android Application
Mark Lester Navarro
 

Recently uploaded (20)

PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
Ad

Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, coding the database class, building and executing queries

  • 1. Database in Android Android Data Managenent using SQL Lite
  • 2. What is SQL lite..? ● ● SQLite is a relational database management system contained in a C programming library. In contrast to many other database management systems, SQLite is not a client–server database engine. Rather, it is embedded into the end program. SQLite is ACID-compliant and implements most of the SQL standard, using a dynamically and weakly typed SQL syntax
  • 3. Origins of sql lite ● ● D. Richard Hipp designed SQLite in the spring of 2000 while working for General Dynamics on contract with the United States Navy. Hipp was designing software used aboard guided missile destroyers, which were originally based on HP-UX with an IBM Informix database back-end. SQLite began as a Tcl extension. The design goals of SQLite were to allow the program to be operated without installing a database management system or requiring a database administrator.
  • 4. Why sql lite ● ● ● ● ● No server is required Object(document) based design Reqire Zero(less) Configration One machine database Multitasking database
  • 5. Using SQL databases in Android Android (as well as iPhone OS) uses an embedded standalone program called sqlite3 which can be used to create a database, indices, views, Insert rows, change rows, define SQL tables, queries, triggers delete rows, run queries and administer a SQLite database file.
  • 6. How to create a SQLitedatabase Open the database according to the flags OPEN_READWRITE OPEN_READONLY CREATE_IF_NECESSARY . Sets the locale of the database to the thesystem's current locale. public static SQLiteDatabase.openDatabase( Stringpath, SQLiteDatabase.CursorFactory factory, int flags ) Parameters path to database file to open and/or create factory an optional factory class that is called to instantiate a cursor when query is called, or null for default flags to control database access mode Returns the newly opened database Throws SQLiteException if the database cannot be opened
  • 7. How to create a SQLitedatabase SQLiteDatabase db=this.openOrCreateDatabase ( "myfriendsDB",MODE_PRIVATE, null); where the assumed prefix for the database stored in the devices ram is: "/data/data/<CURRENT_namespace>/databases/". For instance if this app is created in a namespace called “cis493.sql1”, the full name of the newly created database will be: “/data/data/cis493.sql1/databases/myfriendsDB”. MODEcould be: MODE_PRIVATE, MODE_WORLD_READABLE, and MODE_WORLD_WRITEABLE. Meaningful for apps consisting of multiples activities
  • 8. no Method & Description 1 openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags, DatabaseErrorHandler errorHandler) This method only opens the existing database with the appropriate flag mode. The common flags mode could be OPEN_READWRITE OPEN_READONLY 2 openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags) It is similar to the above method as it also opens the existing database but it does not define any handler to handle the errors of databases
  • 9. no Method & Description 3 openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory) It not only opens but create the database if it not exists. This method is equivalent to openDatabase method 4 openOrCreateDatabase(File file,SQLiteDatabase.CursorFactory factory) It is similar to the above method as it also opens the existing database but it does not define any handler to handle the errors of databases
  • 10. Executing SQL commands on the Database Action queries and Retrieval queries represent the most common operations against the database Retrieval query : typically a SQL-Select command in which a table holding a number of fields and rows is produced as an answer to a data request. Action query : usually performs maintenance and administrative tasks such as manipulating tables, users, environment, etc.
  • 11. Transection Processing The transaction is defined between the methods: beginTransaction and endTransaction. You need to issue the setTransactionSuccessful() call to commit any changes. the absence of it provokes an implicit rollback; consequently the database is reset to the state previous to the beginning of the transaction
  • 12. Creating a Table We will use the execSQL(…)method to manipulate SQL action queries. db.execSQL("create table tblAMIGO(" + " recIDinteger PRIMARY KEY autoincrement, " + " name text, "+ " phone text ); " );
  • 13. Create table The database data types are very simple, for instance we will use: text,varchar, integer, float, numeric, date, time, timestamp, blob, boolean, and so on. 1.In general, any well-formed SQL action command (insert, delete, update, create, drop, alter, etc.) could be framed inside an execSQL(…) method. 2.You should make the call to execSQLinside of a try-catch-finally block. Be aware of potential SQLiteExceptionsituations thrown by the method.
  • 14. Retrieval queries Retrieval queries are SQL-select statements. Android offers two mechanisms for phrasing SQL-select statements: 1.Raw queries take for input a syntactically correct SQL-select statement. The select query could be as complex as needed and involve any number of tables (remember that outer joins are not supported). 2.Simple queries are compact parametized select statements that operate on a single table (for developers who prefer not to use SQL).
  • 15. RawQuery Cursor c1 = db.rawQuery( "select count(*) as Total from Student", null); The rawQuery contains a select-statement that counts the rows in the table Student. 2.The result of this count is held in a table having only one row and one column. The column is called “Total”. 3.The cursor c1will be used to traverse the rows (one!) of the resulting table. 4.Fetching a row using cursor c1 requires advancing to the next record in the answer set. 5.Later the (singleton) field total must be bound to a local Java variable
  • 16. Cursors Android cursor s are used to gain (random) access to tables produced by SQL select statements. Cursors primarily provide one row-at-the-time operations on a table. Cursors include several types of operator 1.Positional awareness operators (isFirst(), isLast(), isBeforeFirst(), isAfterLast()), 2.Record Navigation (moveToFirst(), moveToLast(), moveToNext(), moveToPrevious(), move(n)) 3. Field extraction (getInt, getString, getFloat, getBlob, getDate, etc.) 4.Schema inspection (getColumnName, getColumnNames, getColumnIndex, getColumnCount, getCount)
  • 18. Cursors provide READ_ONLYaccess to records. 2.Early versions of the Android SDK included cursor commands to sequentially modify records. Those operators have been deprecated in Release 1.0. 3.Methods such as cursor.updateInt(...)and cursor.deleteRow(...)are not valid anymore. 4.Instead use an action SQL command in an execSQL(...)method .
  • 19. ParametizedRawQuery String mySQL= "select count(*) as Total " + " from Student" + " where recID> ?" + " and name = ?"; String [] args= {"114337", "Dipak"}; Cursor c1 = db.rawQuery (mySQL, args);
  • 20. Simple Querie Simple queries can only retrieve data from a single table.(non-joining ) it is an template The method’s signature has a fixed sequence of seven arguments representing: 1.the table name, 2.the columns to be retrieved, 3.the search condition (where-clause), 4.arguments for the where-clause, 5.the group-by clause, 6.having-clause, and 7.the order-by clause.
  • 22. SQL Action Queries insert into student values ( ‘Macarena’, ‘555-1234’); update student set name = ‘Maria Macarena’ where phone = ‘555-1234’; delete from where phone = ‘555-1234’; create table Temp ( column1 int, column2 text, column3 date ); drop table Temp;
  • 24. Insert Operator public long insert (String table, String nullColumnHack, ContentValues values)
  • 25. Insertion ● ● execSQL(String sql, Object[ ] bindArgs) This method not only insert data , but also used to update or modify already existing data in database using bind arguments
  • 26. update Operator public int update ( String table, ContentValues values, String whereClause, String[ ] whereArgs) Parameters table : values : the table to update in a map <name,value> from column names to new column values. null is a valid value that will be translated to NULL. whereClause : the optional WHERE clause to apply when updating. Passing null will update all rows. Returns : the number of rows affected
  • 27. delete Operator public int delete( String table, String whereClause , String[ ] whereArgs) Parameters table the table to delete from whereClause the optional WHERE clause to apply when deleting. Passing null will delete all rows. Returns the number of rows affected if a whereClauseis passed in, 0 otherwise. To remove all rows and get a count pass "1" as the whereClause