SQLite Count where query
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开发者_StackOverflow社区 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 likequery(table, columns, selection, selectionArgs, groupBy, having, orderBy)
that spare you from building query strings at risk of SQL injection? EvenrawQuery()
takes query arguments as second parameter.Where do you close your
Cursor
? You'll leak memory this way.What happens if
cursor.moveToFirst()
returnsfalse
and you execute the line after yourif
-block? This will crash.
Check the value of that k variable, it might be not valid for sql IN operator.
精彩评论