Android SQLite API | android database

-Easy to use API, to  access android app's database.

Important classes are 

SQLiteDatabase class that represents the actual database whereas 
SQLiteOpenHelper class, where most of the action takes place. available two methods to override. First, it has an onCreate method, which is called the first time a database is used, and therefore it makes sense that we place our SQL in this method to create our table structure. The other method we must override is onUpgrade, which, as you can probably guess, is called when we upgrade our database (ex. ALTER its structure).

Insert Sql Query:

INSERT INTO StudentsAndGrades  (name, score)  VALUES  ("aashish", 94);

Insert SQL statement:

String name = "aashish"; 
int score = 94;

// Add all the details to the table 
String query = "INSERT INTO " + TABLE_S_AND_G + " (" +    TABLE_ROW_NAME + ", " +    TABLE_ROW_SCORE + ") " +    "VALUES (" +    "'" + name + "'" + ", " +    score +    ");";

private static final String DB_NAME = "MyCollegeDB"; 
private static final String TABLE_S_AND_G = " StudentsAndGrades";
public static final String TABLE_ROW_ID = "_id"; 
public static final String TABLE_ROW_NAME = "name"; 
public static final String TABLE_ROW_SCORE = "score";

Excecute SQL statement:

// This is the actual database 
                                                  private SQLiteDatabase db;
// Create an instance of our internal CustomSQLiteOpenHelper class

CustomSQLiteOpenHelper helper =    new CustomSQLiteOpenHelper(context);

// Get a writable database
             db = helper.getWritableDatabase();

// Run the query 


When adding data to the database, we will use execSQL, as in the previous code, and when getting data from the database, we will use the rawQuery method, as shown in the next code snippet:

Cursor c = db.rawQuery(query, null); 

Note that the rawQuery method returns an object of the Cursor type

Cursor class
. All our database queries will return objects of the Cursor type. We can use the methods of the Cursor class to selectively access the data returned from the queries. example

                              Log.i(c.getString(1), c.getString(2));

Output: logcat the two values stored in the first two columns of the result that the query returned.

 Method to move Cursor to the next row that is ready  for reading:

Other SQL Queries:

Create Table
create table StudentsAndGrades 
_ID integer primary key autoincrement not null,
name text not null,
score int

Insert data

INSERT INTO StudentsAndGrades  (name, score)  VALUES  ("aashish", 23);

Retieve data

SELECT * FROM StudentsAndGrades

Updating database  structure

ALTER TABLE StudentsAndGrades  ADD   age int;


Post a Comment