Вы находитесь на странице: 1из 22

What is SQLite?

SQLite is Open Source Database embedded into Mobile Devices. SQLite supports SQL syntax, transactions and prepared statements. SQLite consumes low memory approx. 250Kbyte. SQLite is a well-regarded relational database management system (RDBMS). It is: Standards-compliant Lightweight Single-tier
each SQLite database is an integrated part of the application that created it. This reduces external dependencies,minimizes latency, and simplifi es transaction locking and synchronization.

SQLite Types
TEXT (String in Java) INTEGER (long in Java) REAL (double in Java) All other types must be converted into one of these fields before getting saved in the database. SQLite itself does not validate if the types written to the columns are actually of the defined type, e.g. you can write an integer into a string column and vice versa.

SQLite in Android
SQLite comes with all Android devices Application database is stored at
DATA/data/APP_NAME/databases/FILENAME Android provides structured data persistence through a

combination of SQLite databases and Content Providers. SQLite databases can be used to store application data using a managed, structured approach. Android offers a full SQLite relational database library. Every application can create its own databases over which it has complete control. Content Providers offer a generic, well-defi ned interface for using and sharing data that provides a consistent abstraction from the underlying data source.

SQLite in Android
Two packages
android.database android.database.sqlite

Content Values are used to insert new rows into tables. Each ContentValues object represents a single table row as a map of column names to values. A Cursor represents the result of a query and basically points to one row of the query result. getCount() moveToFirst() moveToNext() moveToPrevious() getColumnIndexOrThrow Returns the zero-based index for the column with the specified name (throwing an exception if no column exists with that name) getColumnName Returns the name of the specifi ed column index getColumnNames Returns a string array of all the column names in the current Cursor moveToPosition Moves the cursor to the specifi ed row getPosition Returns the current cursor position

Content Values & Cursors

SQLiteOpenHelpler
An abstract class which is responsible for creating, opening, and upgrading a programs database. we need to extend the class with a concrete class, overriding the create() & Upgrade() methods. We also need to make available to this class a database name, table name, and column names. The best way to handle the variables is with constants. Constants ensure that the correct names are always used. Constructor () -call the super() method of SQLiteOpenHelper, specifying the
database name and the current database version.

onCreate(SQLiteDataBase db)-is called by the framework, if the


database is accessed but not yet created.

onUpgrade(SQLiteDatabase db,int oldversion,int newversion)-

called, if the database version is increased in your application code. This method allows you to update an existing database schema or to drop the existing database and recreate it via the onCreate() method.

getReadableDatabase() & getWriteableDatabase() get access to an SQLiteDatabase object; either in read or write mode.

if the database doesnt exist, the helper executes its onCreate handler. If the database version has changed, the onUpgrade handler will fire. In either case, the get<read/writ>ableDatabase call will return the cached, newly opened, newly created, or upgraded database, as appropriate. When a database has been successfully opened, the SQLite Open Helper will cache it, so you can (and should) use these methods each time you query or perform a transaction on the database, rather than caching the open database within your application.

SQLiteDatabase
responsible for communicating changes to the data within the database. SQLiteDatabase is the base class for working with a SQLite database in Android and provides methods to open, query, update and close the database.
it provides the execSQL() method, which allows to execute an SQL statement directly. insert() update() delete() query() rawQuery()

To create a new row, construct a ContentValues object and use its put methods to add name/value pairs representing each column name and its associated value. Insert the new row by passing the Content Values into the insert method called on the target database along with the table name Eg ContentValues values = new ContentValues() ; values.put("username", username) ; values.put("fullname", fullname) ; values.put("password", password) ; database.insert("users", null, values) ;

insert()

Update()
Updating rows is also done with Content Values. Create a new ContentValues object, using the put methods to assign new values to each column you want to update. Call the update method on the database, passing in the table name, the updated Content Values object, and a where clause that specifi es the row(s) to update Eg // Create the updated row Content Values. ContentValues updatedValues = new ContentValues(); // Assign values for each row. updatedValues.put(KEY_GOLD_HOARDED_COLUMN, newHoardValue); // [ ... Repeat for each column to update ... ] // Specify a where clause the defines which rows should be // updated. Specify where arguments as necessary. String where = KEY_ID + = + hoardId; String whereArgs[] = null; // Update the row with the specified index with the new values. SQLiteDatabase db = hoardDBOpenHelper.getWritableDatabase(); db.update(HoardDBOpenHelper.DATABASE_TABLE, updatedValues,where, whereArgs);

Delete()
call the delete method on a database, specifying the table name and a where clause that returns the rows you want to delete Eg // Specify a where clause that determines which row(s) to delete. // Specify where arguments as necessary. String where = KEY_GOLD_HOARDED_COLUMN + = + 0; String whereArgs[] = null; // Delete the rows that match the where clause. SQLiteDatabase db = hoardDBOpenHelper.getWritableDatabase(); db.delete(HoardDBOpenHelper.DATABASE_TABLE, where, whereArgs);

Opening and Creating Databases Without the SQLite Open Helper


to manage the creation, opening, and version control of your databases directly, rather than using the SQLite Open Helper, you can use the application Contexts openOrCreateDatabase method to create the database itself: eg SQLiteDatabase db = context.openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE,null); After you have created the database, you must handle the creation and upgrade logic handled within the onCreate and onUpgrade handlers of the SQLite Open Helper typically using the databases execSQL method to create and drop tables, as required.

Android Database Design Considerations


Files (such as bitmaps or audio fi les) are not usually stored within database tables. Use a string to store a path to the fi le, preferably a fully qualifi ed URI. its strongly recommended that all tables include an auto-increment key fi eld as a unique index fi eld for each row. If you plan to share your table using a Content Provider, a unique ID fi eld is required

Query () Queries can be created via the rawQuery() and query() methods or via the SQLiteQueryBuilder class . rawQuery() - directly accepts an SQL select statement as input. query() - provides a structured interface for specifying the SQL query.

Cursor cursor = database.query( "users", new String[] {"fullname"}, "username = ? and password = ?", new String[]{username, password}, null, null, null) ; The method query() has the following parameters.

Parameter String dbName String[] columnNames

Comment The table name to compile the query against. A list of which table columns to return. Passing "null" will return all columns. Where-clause, i.e. filter for the selection of data, null will select all data. You may include ?s in the "whereClause"". These placeholders will get replaced by the values from the selectionArgs array. A filter declaring how to group rows, null will cause the rows to not be grouped. Filter for the groups, null means no filter. Table columns which will be used to order the data, null means no ordering.

String whereClause

String[] selectionArgs

String[] groupBy String[] having String[] orderBy

If a condition is not required you can pass null, e.g. for the group by clause. The "whereClause" is specified without the word "where", for example a "where" statement might look like: "_id=19 and summary=?". If you specify placeholder values in the where clause via ?, you pass them as the selectionArgs parameter to the query.

rawQuery()
it directly accepts an SQL select statement as input. Cursor cursor = database.rawQuery( "select fullname from users where username = ? and password = ?", new String[] { username, password }) ;

Extracting values from Cursor


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 get the number of elements of the resulting query use the getCount() method. 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. Cursor provides typed get*() methods, e.g. getLong(columnIndex), getString(columnIndex) to access the column data for the current position of the result. The "columnIndex" is the number of the column you are accessing. Cursor also provides the getColumnIndexOrThrow(String) method which allows to get the column index for a column name of the table. A Cursor needs to be closed with the close() method call.

int columnIndex = cursor.getColumnIndex(KEY_COLUMN_1_NAME); if (columnIndex > -1) { String columnValue = cursor.getString(columnIndex); // Do something with the column value. } else { // Do something else if the column doesnt exist. } Eg2 while (cursor.moveToNext()) { float hoard = cursor.getFloat(COLUMN_INDEX); totalHoard += hoard; }

Steps to access database Step1: create a class which extends SQLiteOpenHeper ,overriding the appropriate methods. We also need to make available to this class a database name, table name, and column names. The best way to handle the variables is with constants. Constants ensure that the correct names are always used. private class MyDBHelper extends SQLiteOpenHelper { private static final String CREATE_TABLE="create table users ( id integer primarykey autoincrement, name text not null, pw text not null); public MyDBhelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { try { db.execSQL(CREATE_TABLE); } catch(SQLiteException ex) { ;}}

@Override public void onUpgrade(SQLiteDatabase db, int oldVersion,int newVersion) { db.execSQL("drop table if exists "+Constants.TABLE_NAME); onCreate(db); } } } Step 2 : access the database and perform the required operation Step2.1 : craeate an object of the class which extends from SQLiteOpenHelper . Step 2.2:access the readabale/writable database Step 2.3: perform required operations (insert,update,delete.select)

public class MyDBActivity extends Activity { private SQLiteDatabase db; private final Context context; private final MyDBhelper dbhelper; public void onCreate(Bundle c){ Super.onCreate(c); dbhelper = new MyDBhelper(this, test, null,1); } public void onClick(View v) throws SQLiteException { try { db = dbhelper.getWritableDatabase(); ContentValues Value = new ContentValues(); Value.put(uname,anu); Value.put(pw,anu1 ); db.insert(users, null, Value); }}