Wednesday, March 21, 2012

Difference between rawQuery() and query() in android Sqlite?


Executing Queries

To execute queries, there are two methods:
  1. Execute db.rawQuery method
  2. 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:
  1. String query: The select statement
  2. String[] selection args: The arguments if a WHERE clause is included in the select statement
Notes
  1. The result of a query is returned in Cursor object.
  2. 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:
  1. String Table Name: The name of the table to run the query against
  2. String [ ] columns: The projection of the query, i.e., the columns to retrieve
  3. String WHERE clause: where clause, if none pass null
  4. String [ ] selection args: The parameters of the WHERE clause
  5. String Group by: string specifying group by clause
  6. String Having: A string specifying HAVING clause
  7. String Order By by: A string Order By by clause

















6 comments:

  1. Your choice of colors and font colors makes this site regretable

    ReplyDelete
    Replies
    1. Agreed, what kind of terrible colors you have selected. Made my eyes blur!

      Delete
  2. Bro, change the colors of the font, man. I can see nothing clearly. Good content but bad color choice.

    ReplyDelete
  3. white font colour on white background colour.....ARE YOU DUMB FOOL....HOW CAN WE READ THIS POST IDIOT

    ReplyDelete