execute multiple statement in single rawquery SQLite - android

can we execute multiple statement like SQL Server store procedure with Android SQLite rawquery
Example:
string statement1 ="create temp table .....";
string statement2 ="insert into temptable select ..... table1"
string statement3="insert into temptable select..... table2"
string statement4="select ...... from temptable";
Cursor cur=SQLiteDatabase db = this.getReadableDatabase().rawQuery(statement1+" "+statement2+" "+statement3+" "+statement4, null);
and is there alternate way to achive this?

db.beginTransaction();
try {
db.execSQL(statement1);
db.execSQL(statement2);
db.execSQL(statement3);
Cursor cursor = db.query(temptable, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
At the end use the cursor to get your results.

Related

Use Sqlite group_concat in db.query() instead of rawquery

What is the equivalent for db.query() of following query:
select group_concat(Id, ',') as ids from RECORD_MASTER
Its working fine with rawquery() but I want to implement it in query() function.
You may try this:
db.query(
DATABASE_TABLE,
new String [] {"group_concat(Id, ',') as ids"},
null, null, null, null, null
);
which corresponds to this function declaration:
Cursor query (String table,
String[] columns,
String selection,
String[] selectionArgs,
String groupBy,
String having,
String orderBy)

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()?
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

adding DISTINCT keyword to query() with SQLite in Android

the difference between query() and rawQuery() in SQLite when making more complex SQL queries.
for example
i want to use the SQL keyword DISTINCT, so I don't get any duplicates returned from the database.
i understand how to use rawQuery() method, that way you can put an actual SQL query statement in the method. in this way i can make a standard SQL statement with rawQuery. it would be easy to add the DISTINCT keyword to any SQL statement when using rawQuery()
however, when using the query() method as shown here in this code, I can't just use regular SQL statements. in this case, how would i make a query with the DISTINCT keyword as part of the query? or something with the same functionality?
// get info from country table
public String[] getCountries(int numberOfRows) {
String[] columns = new String[]{COUNTRY_NAME};
String[] countries = new String[numberOfRows];
int counter = 0;
Cursor cursor = sqLiteDatabase.query(COUNTRY_TABLE, columns,
null, null, null, null, null);
if (cursor != null){
while(cursor.moveToNext()){
countries[counter++] = cursor.getString(cursor.getColumnIndex(COUNTRY_NAME));
}
}
return countries;
}
Instead of the...
public Cursor query(String table, String[] columns, String selection,
String[] selectionArgs, String groupBy, String having,
String orderBy)
...method you're using, just use the...
public Cursor query (boolean distinct, String table, String[] columns,
String selection, String[] selectionArgs, String groupBy,
String having, String orderBy, String limit)
...overload and set distinct to true.
The Android docs seem a bit hard to direct link, but the doc page describing both is here.
you can use this,
Cursor cursor = db.query(true, YOUR_TABLE_NAME, new String[] { COLUMN1 ,COLUMN2, COLUMN_NAME_3 }, null, null, COLUMN2, null, null, null);
Here first parameter is used to set the DISTINCT value i.e if set to true it will return distinct column value.
and sixth parameter denotes column name which you want to GROUP BY.
You should use another QUERY function with first DISTINCT boolean parameter set to TRUE
public Cursor query (boolean distinct, String table,...)
this is the function i used in my app for getting distict name from a group table hope you get an idea ,have a look at it.only distinct values will be fetched if the column contains same names
public ArrayList<String> getGroupNames() {
ArrayList<String> groups = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
String[] projection = {COLUMN_GROUP_NAME};
//select distinct values for group name from group table
Cursor cursor = db.query(true,GROUPS_TABLE_NAME, projection, null, null, COLUMN_GROUP_NAME, null, null,null);
if (cursor.moveToFirst()) {
do {
String group=cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_GROUP_NAME));
groups.add(group);
Log.d("group",group+"gp");
}while (cursor.moveToNext());
}
return groups;
}

How to get a cursor with distinct values only?

I want to return a cursor only with distinct values of a column.
The column 'Groups' has more items but with only 2 values: 1,2,1,1,1,2,2,2,1
String[] FROM = {Groups,_ID};
public Cursor getGroups(){
//......
return db.query(TABLE_NAME,FROM,null,null,null,null,null);
}
will return a cursor containing {1,2,1,1,1,2,2,2,1} but I would like to contain just {1,2}.
You can have an sql query like this,
public Cursor usingDistinct(String column_name) {
return db.rawQuery("select DISTINCT "+column_name+" from "+TBL_NAME, null);
}
you can use distinct argument while making query like this:
public Cursor query (boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
Follow this doc for more clearity.
You can use below example query, as you have to give column name for distinct
Cursor cursor = db.query(true, YOUR_TABLE_NAME, new String[] { COLUMN_NAME_1 ,COLUMN_NAME_2, COLUMN_NAME_3 }, null, null, COLUMN_NAME_2, null, null, null);
COLUMN_NAME_2 - name of the column for distinct.
remember to add GROUP BY column names
Use boolean true iin the distinct argument, For example :
public Cursor query (**true**, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit);

Android sql query using WHERE clause

Dear Stack Overflow Community,
I have a question regarding how to incorporate a WHERE clause when querying a sql database in Android. My goal is to return specific records from my database where the date picked by a datepicker matches the date stored.
Here is my code:
private static String datePickerDate = "3/29/2011";
private static String[] FROM = { _ID, NAME, PRICE, DATE, TIME };
private static String ORDER_BY = TIME + " DESC ";
private static String WHERE = DATE + "is like " + datePickerDate;
private Cursor getEvents(){
// Perform a managed Query. The Activity will handle closing
// and re-querying the cursor when needed
SQLiteDatabase db = events.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, FROM, null, null, null, null, ORDER_BY);
startManagingCursor(cursor);
return cursor;
}
My questions are thus:
Where does my "WHERE" statement go?
And is my "WHERE" statement correct?
The documentation I found for db.query doesn't specify if a "WHERE" clause can be used, it just specifies that a "HAVING" clause is possible, but I don't quite think that's what I'm wanting.
db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy)
The selection represents your WHERE clause.
From the doc
selection A filter declaring which
rows to return, formatted as an SQL
WHERE clause (excluding the WHERE
itself). Passing null will return all
rows for the given table.
So you can try this (untested):
private static String WHERE = "DATE like ?";
db.query(table, columns, WHERE , new String[] { datePickerDate }, groupBy, having, orderBy)
If you want to use the WHERE clause, I would suggest using the raw query function in the SQLiteDatabase class, shown here.
This way, you can have the raw query typed out (or in segments) as if you were doing it naturally with SQL.
EDIT: On a side note, the "selection" parameter of the query() function corresponds to the WHERE clause, as noted here
About where you're "WHERE" goes - look here
And regarding the second part, I think you miss the qouts before and after the value, it should be .. like '3/29/2011' and not .. is like 3/29/2011

Categories

Resources