Menus

Thursday, 4 August 2016

Saving Data With SQLite


Android - SQLite Database Tutorial



What is SQLite

SQLite is a opensource 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 e.t.c

SQLite is an in-process library that implements a self-ontainedserverlesszero-configurationtransactional SQL database engine. The code for SQLite is in the public domain and is thus free for use for any purpose, commercial or private.


Features Of SQLite



  • Transactions are atomic, consistent, isolated, and durable (ACID) even after system crashes and power failures.
  • Zero-configuration - no setup or administration needed.
  • Full SQL implementation with advanced features like partial indexes and common table expressions. (Omitted features)
  • A complete database is stored in a single cross-platform disk file. Great for use as an application file format.
  • Supports terabyte-sized databases and gigabyte-sized strings and blobs. (See limits.html.)
  • Small code footprint: less than 500KiB fully configured or much less with optional features omitted.
  • Simple, easy to use API.
  • Written in ANSI-C. TCL bindings included. Bindings for dozens of other languages available separately.
  • Well-commented source code with 100% branch test coverage.
  • Available as a single ANSI-C source-code file that is easy to compile and hence is easy to add into a larger project.
  • Self-contained: no external dependencies.
  • Cross-platform: Android, *BSD, iOS, Linux, Mac, Solaris, VxWorks, and Windows (Win32, WinCE, WinRT) are supported out of the box. Easy to port to other systems.
  • Sources are in the public domain. Use for any purpose.
  • Comes with a standalone command-line interface (CLI) client that can be used to administer SQLite databases.
More details about SQLite






Database - Package

The main package is android.database.sqlite that contains the classes to manage your own databases


Database - Creation


create a database to call this method openOrCreateDatabase with your database name and mode as a parameter. 
It returns an instance of SQLite database which you have to receive in your own object.

Syntax


SQLiteDatabase mydatabase = openOrCreateDatabase("your database name",MODE_PRIVATE,null);



Some other functions available in the database package , that does this job. 
NoMethod & Description
1openDatabase(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
2openDatabase(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
3openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory)
It not only opens but create the database if it not exists. This method is equivalent to openDatabase method
4openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory)
This method is similar to above method but it takes the File object as a path rather then a string. It is equivalent to file.getPath()


Database - Table Creation and Insertion


create table or insert data into table using execSQL method defined in SQLiteDatabase class

mydatabase.execSQL("CREATE TABLE IF NOT EXISTS yii2ideas (Username VARCHAR,Password VARCHAR);");
mydatabase.execSQL("INSERT INTO yii2ideas VALUES('admin','admin');");


Sr.NoMethod & Description
1execSQL(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



Database - Fetching



Retrieve anything from database using an object of the Cursor class. 
We will call a method of this class called rawQuery and it will return a resultset with the cursor pointing to the table. 
We can move the cursor forward and retrieve the data.

Cursor resultSet = mydatbase.rawQuery("Select * from yii2ideas",null);
resultSet.moveToFirst();
String username = resultSet.getString(1);
String password = resultSet.getString(2);

Some other functions available in the Cursor class that allows us to effectively retrieve the data.

Sr.NoMethod & Description
1getColumnCount()
This method return the total number of columns of the table.
2getColumnIndex(String columnName)
This method returns the index number of a column by specifying the name of the column
3getColumnName(int columnIndex)
This method returns the name of the column by specifying the index of the column
4getColumnNames()
This method returns the array of all the column names of the table.
5getCount()
This method returns the total number of rows in the cursor
6getPosition()
This method returns the current position of the cursor in the table
7isClosed()
This method returns true if the cursor is closed and return false otherwise


Database - Helper class


A helper class to manage database creation and version management.
For managing all the operations related to the database , an helper class has been given and is called SQLiteOpenHelper
It automatically manages the creation and update of the database. 
Syntax
public class DBHelper extends SQLiteOpenHelper {
   public DBHelper(){
      super(context,DATABASE_NAME,null,1);
   }
   public void onCreate(SQLiteDatabase db) {}
   public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {}
}




Other SQLite Examples



Insert null in Sqlite table


CREATE TABLE your_table_name
(MainContactName TEXT NOT NULL DEFAULT '')

CREATE TABLE book(_id INTEGER PRIMARY KEY AUTOINCREMENT,book TEXT DEFAULT "abc");

String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_QUEST + " ( "        + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_QUES        + " TEXT, " + KEY_ANSWER+ " TEXT, "+KEY_OPTA +" TEXT NULL, "        +KEY_OPTB +" TEXT NULL, "+KEY_OPTC+" TEXT NULL)";
db.execSQL(sql);











No comments:

Post a Comment