Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance difference between a query() and rawQuery() method in Android

What is the difference between using a

rawQuery(String sql, String[] selectionArgs)

and

query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)

in android?

From my understanding query() method should in turn convert its parameters to form a sql query. So, would rawQuery() method give us better performance over query()?

like image 583
Prasanna Avatar asked Feb 22 '14 17:02

Prasanna


1 Answers

To execute queries, there are two 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

like image 190
Savan Kachhiya Patel Avatar answered Oct 05 '22 12:10

Savan Kachhiya Patel