在我的应用程序中,我需要在“status”列中获取具有特定值的行总数。这是我尝试过的代码,
String unreadquery="(SELECT COUNT(*)FROM TABLE_MESSAGES WHERE KEY_STATUS="0")";
Cursor cursor = db.rawQuery(unreadquery, null);
int a=cursor.getCount();
但它在查询语句中显示错误。如何在特定列中获得具有0值的行数?
谢谢!
这是创建表的代码:
public static final String TABLE_MESSAGES = "Messages";
String CREATE_MESSAGES_TABLE = "CREATE TABLE " + TABLE_MESSAGES + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_FROM + " TEXT," + KEY_TO + " TEXT,"
+ KEY_BODY + " TEXT," + KEY_DATE + " TEXT," + KEY_STATUS + " TEXT" + ")";
db.execSQL(CREATE_MESSAGES_TABLE);
答案 0 :(得分:1)
如果KEY_STATUS
是文本列,请使用单引号。另外,根据您的评论,TABLE_MESSAGES
和KEY_STATUS
是定义表名和列名的常量。
String unreadquery="SELECT COUNT(*) FROM "
+ TABLE_MESSAGES + " WHERE " + KEY_STATUS + "='0'";
答案 1 :(得分:1)
您只在子查询周围使用括号。
此外,TABLE_MESSAGES
和KEY_STATUS
是Java符号,因此您必须将值放入SQL字符串中:
String unreadquery = "SELECT COUNT(*) FROM "+TABLE_MESSAGES+
" WHERE "+KEY_STATUS+" = '0'";
答案 2 :(得分:0)
你可以简单地写
int a=0;
SQLiteDatabase db=this.getReadableDatabase();
String unreadquery="SELECT * FROM TABLE_MESSAGES WHERE KEY_STATUS="0 ";
Cursor cursor=db.rawQuery(unreadquery, null);
cursor.moveToFirst();
if(cursor.getCount()>0)
{
a=cursor.getCount();
}
cursor.close();
db.close();
return a;
答案 3 :(得分:0)
完全照做,只是在查询中删除“ COUNT”,以防万一事先为rawQuery()创建参数,如下所示:
String [] keyStatusValue = {"0"};
String unreadquery="(SELECT * FROM TABLE_MESSAGES WHERE KEY_STATUS =?");
// Notice I didn't add COUNT
// and created a String array no matter if keystatus was set as Integer
Cursor cursor = db.rawQuery(unreadquery, keyStatusValue);
int a=cursor.getCount();
这是我的建议,因为它对我来说很好用。