我有一个方法应该升级给定用户的unreadMessageCount。
public void increaseUnreadMessageCount(int userID) {
String query = "UPDATE " + tableName + " SET " + DatabaseHelper.KEY_USER_UNREAD_MESSAGE_COUNT + " = "
+ DatabaseHelper.KEY_USER_UNREAD_MESSAGE_COUNT + " + 1 WHERE " + DatabaseHelper.KEY_USER_USER_ID
+ " = ?";
Log.i("query", query);
db.rawQuery(query, new String[] { String.valueOf(userID) });
}
这评估为:UPDATE user SET unreadPrivateMessageCount = unreadPrivateMessageCount + 1 WHERE userID = ?
这对我来说是正确的。
但不知何故它不起作用,行总是0。
或者我的SELECT语句错了吗?
public int getUnreadPrivateMessageCount() {
String query = "SELECT SUM(" + DatabaseHelper.KEY_USER_UNREAD_MESSAGE_COUNT + ") AS messageCount FROM "
+ tableName + " WHERE " + DatabaseHelper.KEY_USER_UNREAD_MESSAGE_COUNT + " <> ?";
Log.i("query", query);
Cursor cursor = db.rawQuery(query, new String[] { "0" });
int messageCount = 0;
if (cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
messageCount = cursor.getInt(cursor.getColumnIndexOrThrow("messageCount"));
cursor.close();
} else {
Log.e("getUnreadPrivateMessageCount", "moveToFirst failed");
}
} else {
Log.e("getUnreadPrivateMessageCount", "count 0");
}
return messageCount;
}
此查询的计算结果为SELECT SUM(unreadPrivateMessageCount) AS messageCount FROM user WHERE unreadPrivateMessageCount <> ?
,并且未触发任何错误日志,这对我来说也是正确的。
答案 0 :(得分:1)
rawQuery
用于执行查询,即SELECT语句。
要执行其他SQL语句,请改用execSQL
。
另外,请检查您是否确实要将ID视为字符串。
答案 1 :(得分:0)
如果您的更新语法正确,则:
public void increaseUnreadMessageCount(int userID) {
String query = "UPDATE " + tableName + " SET " + DatabaseHelper.KEY_USER_UNREAD_MESSAGE_COUNT + " = "
+ DatabaseHelper.KEY_USER_UNREAD_MESSAGE_COUNT + " + 1 WHERE " + DatabaseHelper.KEY_USER_USER_ID
+ " = ?";
Log.i("query", query);
db.rawQuery(query, new String[] { String.valueOf(userID) });
}
你在哪里使用:getUnreadPrivateMessageCount()
,没有,所以它必须是这样的:
public void increaseUnreadMessageCount(int userID) {
String query = "UPDATE " + tableName + " SET " + DatabaseHelper.KEY_USER_UNREAD_MESSAGE_COUNT + " = "
+ getUnreadPrivateMessageCount() + " WHERE " + DatabaseHelper.KEY_USER_USER_ID
+ " = ?";
Log.i("query", query);
db.rawQuery(query, new String[] { String.valueOf(userID) });
}
通过这种方式,总未读消息将传递给表。