SlideShare a Scribd company logo
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

More Related Content

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);