Friday, 26 February 2016

Difference between execSQL and rawQuery in android

public void execSQL (String sql)
Execute a single SQL statement without SELECT operation 
I mean, we can use execSQL for CREATEINSERT, UPDATE, DELETE SQL Operations. 

Example-

SQLiteDatabase myDb = getWritableDatabase();

myDb.execSQL("CREATE TABLE IF NOT EXISTS "
                                + TABLE_NAME
                                + " (Word NVARCHAR (100) PRIMARY KEY , WordLength INTEGER, "
                                + " Frequency INTEGER DEFAULT 0, Timestamp DATETIME DEFAULT                                             CURRENT_TIMESTAMP)
                           ");


public Cursor rawQuery (String sql, String[] selectionArgs)
Execute a sql SELECT query using rawQuery which returns Cursor as a result-set . 

Example-

 ArrayList<String> list = new ArrayList<String>();
  try{
SQLiteDatabase myDb = getReadableDatabase();

       Cursor cursor= myDb .rawQuery(" SELECT "+ KEY_TIMESTAMP
                               +" FROM "+ TABLE_NAME +" WHERE "+ KEY_ISCUSTOM +" =1",null);

                        int initialTimeStamp = cursor.getColumnIndex(KEY_TIMESTAMP);
if (cursor.getCount() != 0) {
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor
.moveToNext()) {
list.add(cursor.getString(initialTimeStamp));
}
cursor.close();
}
                     } catch (Exception e) {

// TODO: handle exception
   }

1 comment: