SlideShare una empresa de Scribd logo
1 de 24
Data Handling with
SQLite
-with Jakir Hossain
www.jakir.me
mail@jakir.me
SQLite
 Embedded RDBMS (Relational Database Management System)
 ACID Compliant (Atomicity, Consistency, Isolation, Durability)
 Size – about 257 Kbytes
 Not a client/server architecture
 Accessed via function calls from the application
 Writing (insert, update, delete) locks the database, queries can be done in
parallel
ACID
 Atomicity: Atomicity requires that each transaction is "all or nothing": if one part
of the transaction fails, the entire transaction fails, and the database state is left
unchanged. An atomic system must guarantee atomicity in each and every
situation, including power failures, errors, and crashes
 Consistency: The consistency property ensures that any transaction will bring the
database from one valid state to another. Any data written to the database must
be valid according to all defined rules, including but not limited
to constraints, cascades, triggers, and any combination thereof. This does not
guarantee correctness of the transaction in all ways the application programmer
might have wanted (that is the responsibility of application-level code) but merely
that any programming errors do not violate any defined rules.
 Isolation: The isolation property ensures that the concurrent execution of
transactions results in a system state that would be obtained if transactions were
executed serially, i.e. one after the other. Providing isolation is the main goal
of concurrency control. Depending on concurrency control method, the effects of
an incomplete transaction might not even be visible to another transaction.
 Durability: Durability means that once a transaction has been committed, it will
remain so, even in the event of power loss, crashes, or errors.
http://en.wikipedia.org/wiki/ACID
History
• SQlite is an open source embedded database. The original implementation
was designed by D. Richard Hipp.
• Hipp was designing software used on board guided missile systems and thus
had limited resources to work with.
• The resulting design goals of SQLite were to allow the program to be
operated without a database installation or administration.
Major Users
• Adobe - Uses SQLite in Photoshop and AcrobatAdobe reader. The Application
file Format of SQLite is used in these products.
• Apple - Several functions in Mac OS X use SQLite:
-Apple Mail, -Safari Web Browser, -Apeture
• The iPhone and iPod Touch platforms may also contain SQLite
implementations (unknown due to closed source nature of those systems.)
 Mozilla - Uses SQLite in the Mozilla Firefox Web Browser. SQLite is used in
Firefox to store metadata.
 Google - Google uses SQLite in Google Desktop and in Google Gears. SQLite is
also used in the mobile OS platform, Android. And many more …
Specifications for SQLite
• “SQLite is different from most other SQL database engines in that its primary
design goal is to be simple”
• SQLite works well with:
• Application file format – transactions guarantee ACID, triggers provide undo/redo
feature
• Temporary data analysis – command line client, import CSV files and use sql to
analyze & generate reports
• Testing – stand-in for enterprise DB during application testing (limits potential
damage!)
• Embedded devices – small, reliable and portable
http://www.sqlite.org/whentouse.html
Specifications for SQLite (cont..)
• Portable - uses only ANSI-standard C and VFS, file format is cross platform
(little vs big endian, 32 vs 64 bit)
• Reliable – has 100% test coverage, open source code and bug database,
transactions are ACID even if power fails
• Small – 300 kb library, runs in 16kb stack and 100kb heap
http://www.sqlite.org/about.html
http://www.sqlite.org/testing.html
http://www.sqlite.org/selfcontained.html
Disadvantages
 High concurrency – reader/writer locks on the entire file
 Huge datasets – DB file can’t exceed file system limit or 2TB
 Access control – there isn’t any
(http://www.sqlite.org/different.html)
Unique Features.
• No configuration. Just drop in the C library and go.
• No server process to administer or user accounts to manage.
• Easy to backup and transmit database (just copy the file)
• Dynamic typing for column values, variable lengths for column records
• Query can reference multiple database files
• A few non-standard SQL extensions (mostly for conflict resolution)
• http://www.sqlite.org/different.html
Storage classes
 NULL – null value
 INTEGER - signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the
magnitude of the value
 REAL - a floating point value, 8-byte IEEE floating point number.
 TEXT - text string, stored using the database encoding (UTF-8, UTF-16BE or
UTF-16LE).
 BLOB. The value is a blob of data, stored exactly as it was input.
android.database.sqlite
 Contains the SQLite database management classes that an application would
use to manage its own private database.
android.database.sqlite - Classes
 SQLiteCloseable - An object created from a SQLiteDatabase that can be closed.
 SQLiteCursor - A Cursor implementation that exposes results from a query on a
SQLiteDatabase.
 SQLiteDatabase - Exposes methods to manage a SQLite database.
 SQLiteOpenHelper - A helper class to manage database creation and version
management.
 SQLiteProgram - A base class for compiled SQLite programs.
 SQLiteQuery - A SQLite program that represents a query that reads the resulting
rows into a CursorWindow.
 SQLiteQueryBuilder - a convenience class that helps build SQL queries to be sent
to SQLiteDatabase objects.
 SQLiteStatement - A pre-compiled statement against a SQLiteDatabase that can be
reused.
android.database.sqlite.SQLiteDatabase
 Contains the methods for: creating, opening, closing, inserting, updating,
deleting and quering an SQLite database
 These methods are similar to JDBC but more method oriented than what we
see with JDBC (remember there is not a RDBMS server running)
openOrCreateDatabase( )
 This method will open an existing database or create one in the application
data area
import android.database.sqlite.SQLiteDatabase;
SQLiteDatabase myDatabase;
myDatabase = openOrCreateDatabase ("my_sqlite_database.db" ,
SQLiteDatabase.CREATE_IF_NECESSARY , null);
SQLite Database Properties
 Important database configuration options include: version, locale, and
thread-safe locking.
import java.util.Locale;
myDatabase.setVersion(1);
myDatabase.setLockingEnabled(true);
myDatabase.SetLocale(Locale.getDefault());
Creating Tables
 Create a static string containing the SQLite CREATE statement, use the
execSQL( ) method to execute it.
String createAuthor = "CREAT TABLE authors (
id INTEGER PRIMARY KEY AUTOINCREMENT,
fname TEXT,
lname TEXT);
myDatabase.execSQL(createAuthor);
insert( )
 long insert(String table, String nullColumnHack, ContentValues values)
import android.content.ContentValues;
ContentValues values = new ContentValues( );
values.put("firstname" , "J.K.");
values.put("lastname" , "Rowling");
long newAuthorID = myDatabase.insert("tbl_authors" , "" , values);
update( )
 int update(String table, ContentValues values, String whereClause, String[ ]
whereArgs)
public void updateBookTitle(Integer bookId, String newTitle) {
ContentValues values = new ContentValues();
values.put("title" , newTitle);
myDatabase.update("tbl_books" , values ,
"id=?" , new String[ ] {bookId.toString() } );
}
delete( )
 int delete(String table, String whereClause, String[] whereArgs)
 public void deleteBook(Integer bookId) {
 myDatabase.delete("tbl_books" , "id=?" ,
 new String[ ] { bookId.toString( ) } ) ;
 }
android.database
 http://developer.android.com/reference/android/database/package-
summary.html
 Contains classes and interfaces to explore data returned through a content
provider.
 The main thing we are going to use here is the Cursor interface to get the
data from the resultset that is returned by a query.
 A query returns a Cursor object. A Cursor represents the result of a query and
basically points to one row of the query result. This way Android can buffer
the query results efficiently; as it does not have to load all data into memory.

To move between individual data rows, you can use the moveToFirst() and
moveToNext() methods. The isAfterLast() method allows to check if the end
of the query result has been reached.
http://developer.android.com/reference/android/database/Cursor.html
Queries
 Method of SQLiteDatabase class and performs queries on the DB and
returns the results in a Cursor object
 Cursor c = mdb.query(p1,p2,p3,p4,p5,p6,p7)
 p1 ; Table name (String)
 p2 ; Columns to return (String array)
 p3 ; WHERE clause (use null for all, ?s for selection args)
 p4 ; selection arg values for ?s of WHERE clause
 p5 ; GROUP BY ( null for none) (String)
 p6 ; HAVING (null unless GROUP BY requires one) (String)
 p7 ; ORDER BY (null for default ordering)(String)
 p8 ; LIMIT (null for no limit) (String)
Simple Queries
 SQL - "SELECT * FROM ABC;"
SQLite - Cursor c = mdb.query(abc,null,null,null,null,null,null);
 SQL - "SELECT * FROM ABC WHERE C1=5"
SQLite - Cursor c = mdb.query(
abc,null,"c1=?" , new String[ ] {"5"},null,null,null);
 SQL – "SELECT title,id FROM BOOKS ORDER BY title ASC"
SQLite – String colsToReturn [ ] {"title","id"};
String sortOrder = "title ASC";
Cursor c = mdb.query("books",colsToReturn,
null,null,null,null,sortOrder);
Example
 Visit:
http://www.vogella.com/tutorials/AndroidSQLite/article.html
Questions

Más contenido relacionado

La actualidad más candente

SQLite Database Tutorial In Android
SQLite Database Tutorial In AndroidSQLite Database Tutorial In Android
SQLite Database Tutorial In AndroidAndroid 5
 
Introduction to SQLite: The Most Popular Database in the World
Introduction to SQLite: The Most Popular Database in the WorldIntroduction to SQLite: The Most Popular Database in the World
Introduction to SQLite: The Most Popular Database in the Worldjkreibich
 
Sqlite
SqliteSqlite
SqliteKumar
 
Android Training (Storing data using SQLite)
Android Training (Storing data using SQLite)Android Training (Storing data using SQLite)
Android Training (Storing data using SQLite)Khaled Anaqwa
 
09.1. Android - Local Database (Sqlite)
09.1. Android - Local Database (Sqlite)09.1. Android - Local Database (Sqlite)
09.1. Android - Local Database (Sqlite)Oum Saokosal
 
Dealing with SQL Security from ADO.NET
Dealing with SQL Security from ADO.NETDealing with SQL Security from ADO.NET
Dealing with SQL Security from ADO.NETFernando G. Guerrero
 
JAM819 - Native API Deep Dive: Data Storage and Retrieval
JAM819 - Native API Deep Dive: Data Storage and RetrievalJAM819 - Native API Deep Dive: Data Storage and Retrieval
JAM819 - Native API Deep Dive: Data Storage and RetrievalDr. Ranbijay Kumar
 
Sql server 2012 tutorials writing transact-sql statements
Sql server 2012 tutorials   writing transact-sql statementsSql server 2012 tutorials   writing transact-sql statements
Sql server 2012 tutorials writing transact-sql statementsSteve Xu
 

La actualidad más candente (20)

SQLite Database Tutorial In Android
SQLite Database Tutorial In AndroidSQLite Database Tutorial In Android
SQLite Database Tutorial In Android
 
Database in Android
Database in AndroidDatabase in Android
Database in Android
 
Android Database
Android DatabaseAndroid Database
Android Database
 
Introduction to SQLite: The Most Popular Database in the World
Introduction to SQLite: The Most Popular Database in the WorldIntroduction to SQLite: The Most Popular Database in the World
Introduction to SQLite: The Most Popular Database in the World
 
Sqlite
SqliteSqlite
Sqlite
 
Sqlite
SqliteSqlite
Sqlite
 
SQLITE Android
SQLITE AndroidSQLITE Android
SQLITE Android
 
SQLite 3
SQLite 3SQLite 3
SQLite 3
 
SQLite database in android
SQLite database in androidSQLite database in android
SQLite database in android
 
Android Training (Storing data using SQLite)
Android Training (Storing data using SQLite)Android Training (Storing data using SQLite)
Android Training (Storing data using SQLite)
 
09.1. Android - Local Database (Sqlite)
09.1. Android - Local Database (Sqlite)09.1. Android - Local Database (Sqlite)
09.1. Android - Local Database (Sqlite)
 
ODI User and Security
ODI User and Security ODI User and Security
ODI User and Security
 
Android sq lite-chapter 22
Android sq lite-chapter 22Android sq lite-chapter 22
Android sq lite-chapter 22
 
Sql lite android
Sql lite androidSql lite android
Sql lite android
 
SQLite - Overview
SQLite - OverviewSQLite - Overview
SQLite - Overview
 
Dealing with SQL Security from ADO.NET
Dealing with SQL Security from ADO.NETDealing with SQL Security from ADO.NET
Dealing with SQL Security from ADO.NET
 
JAM819 - Native API Deep Dive: Data Storage and Retrieval
JAM819 - Native API Deep Dive: Data Storage and RetrievalJAM819 - Native API Deep Dive: Data Storage and Retrieval
JAM819 - Native API Deep Dive: Data Storage and Retrieval
 
ASP.NET 09 - ADO.NET
ASP.NET 09 - ADO.NETASP.NET 09 - ADO.NET
ASP.NET 09 - ADO.NET
 
ASP.NET Lecture 4
ASP.NET Lecture 4ASP.NET Lecture 4
ASP.NET Lecture 4
 
Sql server 2012 tutorials writing transact-sql statements
Sql server 2012 tutorials   writing transact-sql statementsSql server 2012 tutorials   writing transact-sql statements
Sql server 2012 tutorials writing transact-sql statements
 

Destacado

FYPJ - Cerebral Android App Development (Report)
FYPJ - Cerebral Android App Development (Report)FYPJ - Cerebral Android App Development (Report)
FYPJ - Cerebral Android App Development (Report)Nehemiah Tan
 
Getting Started With ANDROID
Getting Started With ANDROIDGetting Started With ANDROID
Getting Started With ANDROIDAmit Yadav
 
Apresentacao banco de dados moveis
Apresentacao   banco de dados moveisApresentacao   banco de dados moveis
Apresentacao banco de dados moveisDiogenes Freitas
 
android app development training report
android app development training reportandroid app development training report
android app development training reportRishita Jaggi
 
BroadcastReceivers in Android
BroadcastReceivers in AndroidBroadcastReceivers in Android
BroadcastReceivers in AndroidPerfect APK
 
(続) Effective SQLite for Android
(続) Effective SQLite for Android(続) Effective SQLite for Android
(続) Effective SQLite for AndroidShinobu Okano
 
[2C6]SQLite DB 의 입출력 특성분석 : Android 와 Tizen 사례
[2C6]SQLite DB 의 입출력 특성분석 : Android 와 Tizen 사례[2C6]SQLite DB 의 입출력 특성분석 : Android 와 Tizen 사례
[2C6]SQLite DB 의 입출력 특성분석 : Android 와 Tizen 사례NAVER D2
 
Android telephony stack
Android telephony stackAndroid telephony stack
Android telephony stackDavid Marques
 
Android Telephony Manager and SMS
Android Telephony Manager and SMSAndroid Telephony Manager and SMS
Android Telephony Manager and SMSJussi Pohjolainen
 
Evrdi : Social Diary ( iOS and Android )
Evrdi : Social Diary ( iOS and Android )Evrdi : Social Diary ( iOS and Android )
Evrdi : Social Diary ( iOS and Android )Eakapong Kattiya
 
Capítulo 04 - Persistência de dados com SQLite
Capítulo 04 - Persistência de dados com SQLiteCapítulo 04 - Persistência de dados com SQLite
Capítulo 04 - Persistência de dados com SQLiteMarcio Palheta
 
Apresentação de slides pronto
Apresentação de slides prontoApresentação de slides pronto
Apresentação de slides prontocandidacbertao
 

Destacado (14)

FYPJ - Cerebral Android App Development (Report)
FYPJ - Cerebral Android App Development (Report)FYPJ - Cerebral Android App Development (Report)
FYPJ - Cerebral Android App Development (Report)
 
Getting Started With ANDROID
Getting Started With ANDROIDGetting Started With ANDROID
Getting Started With ANDROID
 
Apresentacao banco de dados moveis
Apresentacao   banco de dados moveisApresentacao   banco de dados moveis
Apresentacao banco de dados moveis
 
android app development training report
android app development training reportandroid app development training report
android app development training report
 
BroadcastReceivers in Android
BroadcastReceivers in AndroidBroadcastReceivers in Android
BroadcastReceivers in Android
 
(続) Effective SQLite for Android
(続) Effective SQLite for Android(続) Effective SQLite for Android
(続) Effective SQLite for Android
 
Sqlite Multiple Table
Sqlite Multiple TableSqlite Multiple Table
Sqlite Multiple Table
 
[2C6]SQLite DB 의 입출력 특성분석 : Android 와 Tizen 사례
[2C6]SQLite DB 의 입출력 특성분석 : Android 와 Tizen 사례[2C6]SQLite DB 의 입출력 특성분석 : Android 와 Tizen 사례
[2C6]SQLite DB 의 입출력 특성분석 : Android 와 Tizen 사례
 
Android telephony stack
Android telephony stackAndroid telephony stack
Android telephony stack
 
Android Telephony Manager and SMS
Android Telephony Manager and SMSAndroid Telephony Manager and SMS
Android Telephony Manager and SMS
 
Android ppt
Android pptAndroid ppt
Android ppt
 
Evrdi : Social Diary ( iOS and Android )
Evrdi : Social Diary ( iOS and Android )Evrdi : Social Diary ( iOS and Android )
Evrdi : Social Diary ( iOS and Android )
 
Capítulo 04 - Persistência de dados com SQLite
Capítulo 04 - Persistência de dados com SQLiteCapítulo 04 - Persistência de dados com SQLite
Capítulo 04 - Persistência de dados com SQLite
 
Apresentação de slides pronto
Apresentação de slides prontoApresentação de slides pronto
Apresentação de slides pronto
 

Similar a Data Handning with Sqlite for Android

Sql data base
Sql data baseSql data base
Sql data baseAli Jafar
 
Access Data from XPages with the Relational Controls
Access Data from XPages with the Relational ControlsAccess Data from XPages with the Relational Controls
Access Data from XPages with the Relational ControlsTeamstudio
 
SQL PPT.pptx
SQL PPT.pptxSQL PPT.pptx
SQL PPT.pptxKulbir4
 
Azure - Data Platform
Azure - Data PlatformAzure - Data Platform
Azure - Data Platformgiventocode
 
SQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginners
SQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginnersSQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginners
SQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginnersTobias Koprowski
 
Scalable relational database with SQL Azure
Scalable relational database with SQL AzureScalable relational database with SQL Azure
Scalable relational database with SQL AzureShy Engelberg
 
Migrating from PHP 4 to PHP 5
Migrating from PHP 4 to PHP 5Migrating from PHP 4 to PHP 5
Migrating from PHP 4 to PHP 5John Coggeshall
 
Sql source control
Sql source controlSql source control
Sql source controlAndyPickett
 
KoprowskiT_SQLSat230_Rheinland_SQLAzure-fromPlantoBackuptoCloud
KoprowskiT_SQLSat230_Rheinland_SQLAzure-fromPlantoBackuptoCloudKoprowskiT_SQLSat230_Rheinland_SQLAzure-fromPlantoBackuptoCloud
KoprowskiT_SQLSat230_Rheinland_SQLAzure-fromPlantoBackuptoCloudTobias Koprowski
 
Azure Data platform
Azure Data platformAzure Data platform
Azure Data platformMostafa
 
Migrating on premises workload to azure sql database
Migrating on premises workload to azure sql databaseMigrating on premises workload to azure sql database
Migrating on premises workload to azure sql databasePARIKSHIT SAVJANI
 
Compare the capabilities of the Microsoft Access, Microsoft SQL Serv.pdf
Compare the capabilities of the Microsoft Access, Microsoft SQL Serv.pdfCompare the capabilities of the Microsoft Access, Microsoft SQL Serv.pdf
Compare the capabilities of the Microsoft Access, Microsoft SQL Serv.pdfarihantplastictanksh
 
ScaleBase Webinar: Scaling MySQL - Sharding Made Easy!
ScaleBase Webinar: Scaling MySQL - Sharding Made Easy!ScaleBase Webinar: Scaling MySQL - Sharding Made Easy!
ScaleBase Webinar: Scaling MySQL - Sharding Made Easy!ScaleBase
 

Similar a Data Handning with Sqlite for Android (20)

Sql Sever Presentation.pptx
Sql Sever Presentation.pptxSql Sever Presentation.pptx
Sql Sever Presentation.pptx
 
Sql data base
Sql data baseSql data base
Sql data base
 
Access Data from XPages with the Relational Controls
Access Data from XPages with the Relational ControlsAccess Data from XPages with the Relational Controls
Access Data from XPages with the Relational Controls
 
SQL PPT.pptx
SQL PPT.pptxSQL PPT.pptx
SQL PPT.pptx
 
Azure - Data Platform
Azure - Data PlatformAzure - Data Platform
Azure - Data Platform
 
SQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginners
SQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginnersSQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginners
SQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginners
 
Scalable relational database with SQL Azure
Scalable relational database with SQL AzureScalable relational database with SQL Azure
Scalable relational database with SQL Azure
 
Why you should(n't) run your databases in the cloud
Why you should(n't) run your databases in the cloudWhy you should(n't) run your databases in the cloud
Why you should(n't) run your databases in the cloud
 
Os Owens
Os OwensOs Owens
Os Owens
 
Database CI/CD Pipeline
Database CI/CD PipelineDatabase CI/CD Pipeline
Database CI/CD Pipeline
 
Chap3 3 12
Chap3 3 12Chap3 3 12
Chap3 3 12
 
Migrating from PHP 4 to PHP 5
Migrating from PHP 4 to PHP 5Migrating from PHP 4 to PHP 5
Migrating from PHP 4 to PHP 5
 
Sql source control
Sql source controlSql source control
Sql source control
 
KoprowskiT_SQLSat230_Rheinland_SQLAzure-fromPlantoBackuptoCloud
KoprowskiT_SQLSat230_Rheinland_SQLAzure-fromPlantoBackuptoCloudKoprowskiT_SQLSat230_Rheinland_SQLAzure-fromPlantoBackuptoCloud
KoprowskiT_SQLSat230_Rheinland_SQLAzure-fromPlantoBackuptoCloud
 
Day2
Day2Day2
Day2
 
Azure Data platform
Azure Data platformAzure Data platform
Azure Data platform
 
Migrating on premises workload to azure sql database
Migrating on premises workload to azure sql databaseMigrating on premises workload to azure sql database
Migrating on premises workload to azure sql database
 
Mysql
MysqlMysql
Mysql
 
Compare the capabilities of the Microsoft Access, Microsoft SQL Serv.pdf
Compare the capabilities of the Microsoft Access, Microsoft SQL Serv.pdfCompare the capabilities of the Microsoft Access, Microsoft SQL Serv.pdf
Compare the capabilities of the Microsoft Access, Microsoft SQL Serv.pdf
 
ScaleBase Webinar: Scaling MySQL - Sharding Made Easy!
ScaleBase Webinar: Scaling MySQL - Sharding Made Easy!ScaleBase Webinar: Scaling MySQL - Sharding Made Easy!
ScaleBase Webinar: Scaling MySQL - Sharding Made Easy!
 

Último

System Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingSystem Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingBootNeck1
 
signals in triangulation .. ...Surveying
signals in triangulation .. ...Surveyingsignals in triangulation .. ...Surveying
signals in triangulation .. ...Surveyingsapna80328
 
DEVICE DRIVERS AND INTERRUPTS SERVICE MECHANISM.pdf
DEVICE DRIVERS AND INTERRUPTS  SERVICE MECHANISM.pdfDEVICE DRIVERS AND INTERRUPTS  SERVICE MECHANISM.pdf
DEVICE DRIVERS AND INTERRUPTS SERVICE MECHANISM.pdfAkritiPradhan2
 
Python Programming for basic beginners.pptx
Python Programming for basic beginners.pptxPython Programming for basic beginners.pptx
Python Programming for basic beginners.pptxmohitesoham12
 
"Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ..."Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ...Erbil Polytechnic University
 
Mine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxMine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxRomil Mishra
 
Levelling - Rise and fall - Height of instrument method
Levelling - Rise and fall - Height of instrument methodLevelling - Rise and fall - Height of instrument method
Levelling - Rise and fall - Height of instrument methodManicka Mamallan Andavar
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionMebane Rash
 
Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________Romil Mishra
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating SystemRashmi Bhat
 
Research Methodology for Engineering pdf
Research Methodology for Engineering pdfResearch Methodology for Engineering pdf
Research Methodology for Engineering pdfCaalaaAbdulkerim
 
TEST CASE GENERATION GENERATION BLOCK BOX APPROACH
TEST CASE GENERATION GENERATION BLOCK BOX APPROACHTEST CASE GENERATION GENERATION BLOCK BOX APPROACH
TEST CASE GENERATION GENERATION BLOCK BOX APPROACHSneha Padhiar
 
SOFTWARE ESTIMATION COCOMO AND FP CALCULATION
SOFTWARE ESTIMATION COCOMO AND FP CALCULATIONSOFTWARE ESTIMATION COCOMO AND FP CALCULATION
SOFTWARE ESTIMATION COCOMO AND FP CALCULATIONSneha Padhiar
 
Robotics Group 10 (Control Schemes) cse.pdf
Robotics Group 10  (Control Schemes) cse.pdfRobotics Group 10  (Control Schemes) cse.pdf
Robotics Group 10 (Control Schemes) cse.pdfsahilsajad201
 
『澳洲文凭』买麦考瑞大学毕业证书成绩单办理澳洲Macquarie文凭学位证书
『澳洲文凭』买麦考瑞大学毕业证书成绩单办理澳洲Macquarie文凭学位证书『澳洲文凭』买麦考瑞大学毕业证书成绩单办理澳洲Macquarie文凭学位证书
『澳洲文凭』买麦考瑞大学毕业证书成绩单办理澳洲Macquarie文凭学位证书rnrncn29
 
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.elesangwon
 
Comprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdfComprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdfalene1
 
Novel 3D-Printed Soft Linear and Bending Actuators
Novel 3D-Printed Soft Linear and Bending ActuatorsNovel 3D-Printed Soft Linear and Bending Actuators
Novel 3D-Printed Soft Linear and Bending ActuatorsResearcher Researcher
 
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...Sumanth A
 
KCD Costa Rica 2024 - Nephio para parvulitos
KCD Costa Rica 2024 - Nephio para parvulitosKCD Costa Rica 2024 - Nephio para parvulitos
KCD Costa Rica 2024 - Nephio para parvulitosVictor Morales
 

Último (20)

System Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingSystem Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event Scheduling
 
signals in triangulation .. ...Surveying
signals in triangulation .. ...Surveyingsignals in triangulation .. ...Surveying
signals in triangulation .. ...Surveying
 
DEVICE DRIVERS AND INTERRUPTS SERVICE MECHANISM.pdf
DEVICE DRIVERS AND INTERRUPTS  SERVICE MECHANISM.pdfDEVICE DRIVERS AND INTERRUPTS  SERVICE MECHANISM.pdf
DEVICE DRIVERS AND INTERRUPTS SERVICE MECHANISM.pdf
 
Python Programming for basic beginners.pptx
Python Programming for basic beginners.pptxPython Programming for basic beginners.pptx
Python Programming for basic beginners.pptx
 
"Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ..."Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ...
 
Mine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxMine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptx
 
Levelling - Rise and fall - Height of instrument method
Levelling - Rise and fall - Height of instrument methodLevelling - Rise and fall - Height of instrument method
Levelling - Rise and fall - Height of instrument method
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of Action
 
Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating System
 
Research Methodology for Engineering pdf
Research Methodology for Engineering pdfResearch Methodology for Engineering pdf
Research Methodology for Engineering pdf
 
TEST CASE GENERATION GENERATION BLOCK BOX APPROACH
TEST CASE GENERATION GENERATION BLOCK BOX APPROACHTEST CASE GENERATION GENERATION BLOCK BOX APPROACH
TEST CASE GENERATION GENERATION BLOCK BOX APPROACH
 
SOFTWARE ESTIMATION COCOMO AND FP CALCULATION
SOFTWARE ESTIMATION COCOMO AND FP CALCULATIONSOFTWARE ESTIMATION COCOMO AND FP CALCULATION
SOFTWARE ESTIMATION COCOMO AND FP CALCULATION
 
Robotics Group 10 (Control Schemes) cse.pdf
Robotics Group 10  (Control Schemes) cse.pdfRobotics Group 10  (Control Schemes) cse.pdf
Robotics Group 10 (Control Schemes) cse.pdf
 
『澳洲文凭』买麦考瑞大学毕业证书成绩单办理澳洲Macquarie文凭学位证书
『澳洲文凭』买麦考瑞大学毕业证书成绩单办理澳洲Macquarie文凭学位证书『澳洲文凭』买麦考瑞大学毕业证书成绩单办理澳洲Macquarie文凭学位证书
『澳洲文凭』买麦考瑞大学毕业证书成绩单办理澳洲Macquarie文凭学位证书
 
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
 
Comprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdfComprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdf
 
Novel 3D-Printed Soft Linear and Bending Actuators
Novel 3D-Printed Soft Linear and Bending ActuatorsNovel 3D-Printed Soft Linear and Bending Actuators
Novel 3D-Printed Soft Linear and Bending Actuators
 
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
 
KCD Costa Rica 2024 - Nephio para parvulitos
KCD Costa Rica 2024 - Nephio para parvulitosKCD Costa Rica 2024 - Nephio para parvulitos
KCD Costa Rica 2024 - Nephio para parvulitos
 

Data Handning with Sqlite for Android

  • 1. Data Handling with SQLite -with Jakir Hossain www.jakir.me mail@jakir.me
  • 2. SQLite  Embedded RDBMS (Relational Database Management System)  ACID Compliant (Atomicity, Consistency, Isolation, Durability)  Size – about 257 Kbytes  Not a client/server architecture  Accessed via function calls from the application  Writing (insert, update, delete) locks the database, queries can be done in parallel
  • 3. ACID  Atomicity: Atomicity requires that each transaction is "all or nothing": if one part of the transaction fails, the entire transaction fails, and the database state is left unchanged. An atomic system must guarantee atomicity in each and every situation, including power failures, errors, and crashes  Consistency: The consistency property ensures that any transaction will bring the database from one valid state to another. Any data written to the database must be valid according to all defined rules, including but not limited to constraints, cascades, triggers, and any combination thereof. This does not guarantee correctness of the transaction in all ways the application programmer might have wanted (that is the responsibility of application-level code) but merely that any programming errors do not violate any defined rules.  Isolation: The isolation property ensures that the concurrent execution of transactions results in a system state that would be obtained if transactions were executed serially, i.e. one after the other. Providing isolation is the main goal of concurrency control. Depending on concurrency control method, the effects of an incomplete transaction might not even be visible to another transaction.  Durability: Durability means that once a transaction has been committed, it will remain so, even in the event of power loss, crashes, or errors. http://en.wikipedia.org/wiki/ACID
  • 4. History • SQlite is an open source embedded database. The original implementation was designed by D. Richard Hipp. • Hipp was designing software used on board guided missile systems and thus had limited resources to work with. • The resulting design goals of SQLite were to allow the program to be operated without a database installation or administration.
  • 5. Major Users • Adobe - Uses SQLite in Photoshop and AcrobatAdobe reader. The Application file Format of SQLite is used in these products. • Apple - Several functions in Mac OS X use SQLite: -Apple Mail, -Safari Web Browser, -Apeture • The iPhone and iPod Touch platforms may also contain SQLite implementations (unknown due to closed source nature of those systems.)  Mozilla - Uses SQLite in the Mozilla Firefox Web Browser. SQLite is used in Firefox to store metadata.  Google - Google uses SQLite in Google Desktop and in Google Gears. SQLite is also used in the mobile OS platform, Android. And many more …
  • 6. Specifications for SQLite • “SQLite is different from most other SQL database engines in that its primary design goal is to be simple” • SQLite works well with: • Application file format – transactions guarantee ACID, triggers provide undo/redo feature • Temporary data analysis – command line client, import CSV files and use sql to analyze & generate reports • Testing – stand-in for enterprise DB during application testing (limits potential damage!) • Embedded devices – small, reliable and portable http://www.sqlite.org/whentouse.html
  • 7. Specifications for SQLite (cont..) • Portable - uses only ANSI-standard C and VFS, file format is cross platform (little vs big endian, 32 vs 64 bit) • Reliable – has 100% test coverage, open source code and bug database, transactions are ACID even if power fails • Small – 300 kb library, runs in 16kb stack and 100kb heap http://www.sqlite.org/about.html http://www.sqlite.org/testing.html http://www.sqlite.org/selfcontained.html
  • 8. Disadvantages  High concurrency – reader/writer locks on the entire file  Huge datasets – DB file can’t exceed file system limit or 2TB  Access control – there isn’t any (http://www.sqlite.org/different.html)
  • 9. Unique Features. • No configuration. Just drop in the C library and go. • No server process to administer or user accounts to manage. • Easy to backup and transmit database (just copy the file) • Dynamic typing for column values, variable lengths for column records • Query can reference multiple database files • A few non-standard SQL extensions (mostly for conflict resolution) • http://www.sqlite.org/different.html
  • 10. Storage classes  NULL – null value  INTEGER - signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value  REAL - a floating point value, 8-byte IEEE floating point number.  TEXT - text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16LE).  BLOB. The value is a blob of data, stored exactly as it was input.
  • 11. android.database.sqlite  Contains the SQLite database management classes that an application would use to manage its own private database.
  • 12. android.database.sqlite - Classes  SQLiteCloseable - An object created from a SQLiteDatabase that can be closed.  SQLiteCursor - A Cursor implementation that exposes results from a query on a SQLiteDatabase.  SQLiteDatabase - Exposes methods to manage a SQLite database.  SQLiteOpenHelper - A helper class to manage database creation and version management.  SQLiteProgram - A base class for compiled SQLite programs.  SQLiteQuery - A SQLite program that represents a query that reads the resulting rows into a CursorWindow.  SQLiteQueryBuilder - a convenience class that helps build SQL queries to be sent to SQLiteDatabase objects.  SQLiteStatement - A pre-compiled statement against a SQLiteDatabase that can be reused.
  • 13. android.database.sqlite.SQLiteDatabase  Contains the methods for: creating, opening, closing, inserting, updating, deleting and quering an SQLite database  These methods are similar to JDBC but more method oriented than what we see with JDBC (remember there is not a RDBMS server running)
  • 14. openOrCreateDatabase( )  This method will open an existing database or create one in the application data area import android.database.sqlite.SQLiteDatabase; SQLiteDatabase myDatabase; myDatabase = openOrCreateDatabase ("my_sqlite_database.db" , SQLiteDatabase.CREATE_IF_NECESSARY , null);
  • 15. SQLite Database Properties  Important database configuration options include: version, locale, and thread-safe locking. import java.util.Locale; myDatabase.setVersion(1); myDatabase.setLockingEnabled(true); myDatabase.SetLocale(Locale.getDefault());
  • 16. Creating Tables  Create a static string containing the SQLite CREATE statement, use the execSQL( ) method to execute it. String createAuthor = "CREAT TABLE authors ( id INTEGER PRIMARY KEY AUTOINCREMENT, fname TEXT, lname TEXT); myDatabase.execSQL(createAuthor);
  • 17. insert( )  long insert(String table, String nullColumnHack, ContentValues values) import android.content.ContentValues; ContentValues values = new ContentValues( ); values.put("firstname" , "J.K."); values.put("lastname" , "Rowling"); long newAuthorID = myDatabase.insert("tbl_authors" , "" , values);
  • 18. update( )  int update(String table, ContentValues values, String whereClause, String[ ] whereArgs) public void updateBookTitle(Integer bookId, String newTitle) { ContentValues values = new ContentValues(); values.put("title" , newTitle); myDatabase.update("tbl_books" , values , "id=?" , new String[ ] {bookId.toString() } ); }
  • 19. delete( )  int delete(String table, String whereClause, String[] whereArgs)  public void deleteBook(Integer bookId) {  myDatabase.delete("tbl_books" , "id=?" ,  new String[ ] { bookId.toString( ) } ) ;  }
  • 20. android.database  http://developer.android.com/reference/android/database/package- summary.html  Contains classes and interfaces to explore data returned through a content provider.  The main thing we are going to use here is the Cursor interface to get the data from the resultset that is returned by a query.  A query returns a Cursor object. A Cursor represents the result of a query and basically points to one row of the query result. This way Android can buffer the query results efficiently; as it does not have to load all data into memory.  To move between individual data rows, you can use the moveToFirst() and moveToNext() methods. The isAfterLast() method allows to check if the end of the query result has been reached. http://developer.android.com/reference/android/database/Cursor.html
  • 21. Queries  Method of SQLiteDatabase class and performs queries on the DB and returns the results in a Cursor object  Cursor c = mdb.query(p1,p2,p3,p4,p5,p6,p7)  p1 ; Table name (String)  p2 ; Columns to return (String array)  p3 ; WHERE clause (use null for all, ?s for selection args)  p4 ; selection arg values for ?s of WHERE clause  p5 ; GROUP BY ( null for none) (String)  p6 ; HAVING (null unless GROUP BY requires one) (String)  p7 ; ORDER BY (null for default ordering)(String)  p8 ; LIMIT (null for no limit) (String)
  • 22. Simple Queries  SQL - "SELECT * FROM ABC;" SQLite - Cursor c = mdb.query(abc,null,null,null,null,null,null);  SQL - "SELECT * FROM ABC WHERE C1=5" SQLite - Cursor c = mdb.query( abc,null,"c1=?" , new String[ ] {"5"},null,null,null);  SQL – "SELECT title,id FROM BOOKS ORDER BY title ASC" SQLite – String colsToReturn [ ] {"title","id"}; String sortOrder = "title ASC"; Cursor c = mdb.query("books",colsToReturn, null,null,null,null,sortOrder);