开发者

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 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜