SQLite Count where query - android

I use a simple sql lite query to fetch the count value from a table.
Cursor cursor = db.rawQuery("SELECT sum(name2) FROM " + TABLE_NAME, null);
if (cursor.moveToFirst()) {
return cursor.getInt(0);
}
return cursor.getInt(0);
This works good
But when I add a where clause to the select query
Cursor cursor = db.rawQuery("SELECT sum(name2) FROM " + TABLE_NAME + "WHERE name in (" + k + ")", null);
if(cursor.moveToFirst()) {
return cursor.getInt(0);
}
return cursor.getInt(0);
process stops unexpectedly.......

You're missing a space in front of the WHERE: ... + TABLE_NAME + "WHERE name ...
But there's a lot wrong with your code:
Why do you use rawQuery() when there's nice methods like query(table, columns, selection, selectionArgs, groupBy, having, orderBy) that spare you from building query strings at risk of SQL injection? Even rawQuery() takes query arguments as second parameter.
Where do you close your Cursor? You'll leak memory this way.
What happens if cursor.moveToFirst() returns false and you execute the line after your if-block? This will crash.

Check the value of that k variable, it might be not valid for sql IN operator.

Related

how to filter multiple data on multiple column sqlite database

i want to filter multiple data such as
id = "1,3,5" from columnid which is having 1 to 10 id
and another column such as name
name = "a,e,d" from name column of 10 records
and another criteria such as age
age = "21,23,20" from age column of 10 records from same table,
one example i got is
Cursor cursor = db.query("TABLE_NAME",new String[]{"ColumnName"}, "ColumnName=?",new String[]{"value"}, null, null, null);
which is just for one column but i want to get data from multiple column, can anyone help me?
try this working example,
Cursor cursor =
db.query(TABLE_DIARYENTRIES,
new String[] {},
STUDENT_ID + " IN ("+resultStudent+")"+ " AND " +CLASS_NAME + " IN ("+resultClass+")"
+ " AND " +SUBJECT_NAME + " IN ("+resultSubject+")"
null, null, null, null);
and your result string should be 'a','b','c'
I really like the way Google's example is structured. Because for noobies such as myself it makes it really clear what I am doing. And it is also more robust to SQL injections. Here is my modified version of the Google example:
//Column(s) I want returned
String[] projection = {"ColumnIWantReturned"};
//Column(s) I want to filer on
String selection = "FilterColumn1 IN (?) and FilterColumn2 IN (?, ?)";
String[] selectionArgs = {"ArgumentForFilterColumn1", "FirstArgumentForFilterColumn2", "SecondArgumentForFilterColumn2"};
Cursor cursor = db.query(
"MyTable", // The table to query
projection, // The array of columns to return (pass null to get all)
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null // The sort order
);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Log.d("this-is-a-test", cursor.getString(0));
cursor.moveToNext();
}
cursor.close();

SQL Sorting number - ANDROID

public static final String KEY_HIGH
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_HIGH + " INTERGE);"
);
}
public long createEntry(String high) {
ContentValues cv = new ContentValues();
cv.put(KEY_HIGH, high);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
String[] columns = new String[]{KEY_HIGH,KEY_NAME};
Cursor c = ourDatabase.query(
DATABASE_TABLE,
columns, null, null, null, null, KEY_HIGH + " DESC");
I am trying to sort by the column KEY_HIGH, however, the result came out like this:
4
3
2
10
11
1
How do I sort them as numbers from highest to lowest?
thanks.
From the Android docs:
public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
Added in API level 1
Query the given table, returning a Cursor over the result set.
Parameters
table The table name to compile the query against.
columns A list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.
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.
selectionArgs You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings.
groupBy A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped.
having A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null will cause all row groups to be included, and is required when row grouping is not being used.
orderBy How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.
Returns
A Cursor object, which is positioned before the first entry. Note that Cursors are not synchronized, see the documentation for more details.
See Also
Cursor
Note that the final is named orderBy. This is where you can specify which column (or columns) to sort on. Also note that you do not need to include the "ORDER BY" keywords that you would use in a SQL statement.
I was having the same problem.It has a very simple solution:
In your CREATE_TABLE statement do this: " INTEGER, "+KEY_HIGH+ //your remaining things.
no need for the comma after the last null
Cursor c = ourDatabase.query(
DATABASE_TABLE,
columns, null, null, null, null + " ORDER BY " + KEY_HIGH + " DESC");

SQL using with clause not working

My question is why this query does not work?
Cursor c = db.rawQuery("SELECT * FROM tbl_staff WHERE PMajor = '%" + spin.getSelectedItem().toString() + "%'", null);
Cursor c: it is a cursor for handling my query
tbl_staff: my table that consist of PName, PMajor, PCert
spin: is spinner that has values which I need for my database query.
When I use:
if (c.moveToNext())
else (log.d("error query","couldn't do the query!");)
It goes to else statement and moveToNext() doesn't work.
Instead of using =, which checks for equality, use keyword LIKE, which matches a pattern.
Cursor c = db.rawQuery("SELECT * FROM tbl_staff WHERE PMajor LIKE '%" + spin.getSelectedItem().toString() + "%'", null);

Multiple OrderBy in SQLiteDatabase.Query Method

I am using the query method of SQLiteDatabase. I need help with the orderBy parameter of this method.
Cursor cursor = sqLiteDatabase.query(tableName, tableColumns, whereClause, whereArgs, groupBy, having, orderBy);
public Cursor getAllCustomexp(int TID) throws SQLException
{
Cursor mCursor =
db.query(false, CEXP_TABLE, new String[] {KEY_CEID, FLD_CETID, FLD_CEEID, FLD_CEMID,
FLD_CEAMT, FLD_CESEL}, FLD_CETID + " = " + TID, null,
null, null, FLD_CEEID, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
Question 1:
In the above query the result set will be sorted by FLD_CEEID in ascending or descending order ?
Question 2:
If I need to order the result set first by FLD_CEEID and then by FLD_CEMID how should i construct the order by parameter of this query.
Is it possible to do multiple order by using this method?
From SQLite docs:
If a SELECT statement that returns more than one row does not have an
ORDER BY clause, the order in which the rows are returned is
undefined. Or, if a SELECT statement does have an ORDER BY clause,
then the list of expressions attached to the ORDER BY determine the
order in which rows are returned to the user. Rows are first sorted
based on the results of evaluating the left-most expression in the
ORDER BY list, then ties are broken by evaluating the second left-most
expression and so on. The order in which two rows for which all ORDER
BY expressions evaluate to equal values are returned is undefined.
Each ORDER BY expression may be optionally followed by one of the
keywords ASC (smaller values are returned first) or DESC (larger
values are returned first). If neither ASC or DESC are specified, rows
are sorted in ascending (smaller values first) order by default.
Answer 1: Result set will be sorted in ascending order.
Answer 2:
String orderBy = FLD_CEEID + " ASC, " + FLD_CEMID + " ASC";
db.query(false, CEXP_TABLE, new String[] {KEY_CEID, FLD_CETID, FLD_CEEID, FLD_CEMID,
FLD_CEAMT, FLD_CESEL}, FLD_CETID + " = " + TID, null,
null, null, orderBy, null);
It works like in SQL Select Order By. You can find details here: http://en.wikipedia.org/wiki/Order_by_(SQL) .

How to select distinct values from one column in table?

I am developing a restaurant menu app in Android. My app has one database table which has the following columns:
id (primary key)
category
item name
The category column shows the category of item such as veg, non veg, snacks etc. It has duplicate values and I want to select only distinct values from this column. I have tried the following but it is not working if anyone can provide a solution:
String query = "SELECT DISTINCT category FROM todo";
Cursor cursor = database.rawQuery(query,null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
You can also use this specific query-Method of the SQLiteDatabase class that takes a boolean value to determine whether you want distinct values or not:
public Cursor query (boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
Link to Android Reference
This way you don't have to use rawQuery at all.
Try:
"SELECT DISTINCT category as _id, category FROM todo"
This worked for me in the same situation.
This is how i make distinct, also to get categories
// Get Categories
public Cursor getCategories() {
Cursor c = db.rawQuery("SELECT DISTINCT " + KEY_ITEM_CAT + " as " + KEY_ITEM_ID
+ ", " + KEY_ITEM_CAT + " FROM " + ITEMS_TABLE_NAME, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
I was searching for the same question, and I found something which is direct to the solution in the most simplest way! Check out this answer:
https://stackoverflow.com/a/13879436/4072073

Categories

Resources