Tuesday, 18 December 2012

Difference Between query and rawQuery in Android

In Android  Executing Queries using below methods

    Execute db.rawQuery method
    Execute db.query method


To execute a raw query to retrieve all departments:

Cursor getAllDepts()
  {
   SQLiteDatabase db=this.getReadableDatabase();
   Cursor cur=db.rawQuery("SELECT "+colDeptID+" as _id,
        "+colDeptName+" from "+deptTable,new String [] {});

   return cur;
  }

The rawQuery method has two parameters:

    String query: The select statement
    String[] selection args: The arguments if a WHERE clause is included in the select statement

Notes
The result of a query is returned in Cursor object.In a select statement if the primary key column (the id column) of the table has a name other than _id, then you have to use an alias in the form SELECT [Column Name] as _id cause the Cursor object always expects that the primary key column has the name _id or it will throw an exception .

Another way to perform a query is to use a db.query method. A query to select all employees in a certain department from a view would be like this:

public Cursor getEmpByDept(String Dept) {
   SQLiteDatabase db=this.getReadableDatabase();
   String [] columns=new String[]{"_id",colName,colAge,colDeptName};
   Cursor c=db.query(viewEmps, columns, colDeptName+"=?",
        new String[]{Dept}, null, null, null);
   return c;
  }

The db.query has the following parameters:

    String Table Name: The name of the table to run the query against
    String [ ] columns: The projection of the query, i.e., the columns to retrieve
    String WHERE clause: where clause, if none pass null
    String [ ] selection args: The parameters of the WHERE clause
    String Group by: A string specifying group by clause
    String Having: A string specifying HAVING clause
    String Order By by: A string Order By by clause

Content From:-shuklaxyz

No comments:

Post a Comment

Android SQLite Database Viewer or Debuging with Stetho

Every Android Developer uses SQLite Database to store data into the Android Application data. But to view the data in SQLite have a lot of...