2012-03-16 78 views
1

我有疑問有待澄清。我如何獲取插入到sqlite數據庫的最後一個值。我需要的代碼。我嘗試使用這樣的查詢:我如何獲取插入到sqlite數據庫的最後一個值

SELECT uname,umessage,utime FROM chatmessage ORDER BY utime DESC limit 1; 

我在哪裏做錯了?我在這個問題上需要幫助。

在此先感謝。

回答

0

如果值是最後它的ID應該是最大

你可以解僱這樣

c = db.rawQuery("SELECT uname,umessage,utime FROM tablename WHERE " + 
       "Id = (SELECT MAX(Id) FROM tablename); ",null); 

查詢由特定用戶最後一條消息在消息表像添加用戶ID列

id | userid | message | utime 


1 | 1 | wlhf | 3:10 

2 | 3 | dfhhfjh | 2:15 

3 | 1 | kjfedhr | 4:00 

4 | 2 | hejhe | 1:15 

5 | 3 | kegekr | 3:30 

6 | 1 | wlhf | 3:10 

7 | 3 | dfhhfjh | 2:15 

8 | 1 | kjfedhr | 4:00 

9 | 2 | hejhe | 1:15 

10 | 3 | kegekr | 3:30 




c = db.rawQuery(" 
select message from table1 where 


userid = 1 ; ",null); 




recieve like 



ArrayList<String> listMessg = new ArrayList<String>(); 



cursor = dbm.columnValueofCourse(); 
     cursor.moveToFirst(); 
     startManagingCursor(cursor); 

for (int i = 0; i < cursor.getCount(); i++) { 

    reciv = cursor.getString(cursor 
        .getColumnIndex("message")); 
listMessg.add(reciv_Par); 
} 

int sizeoflist = listMessg.size(); 

because in ascending order , the last index 
of array list will be the last message of the user 

System.out.println("THE LAST MESSAGE BY USER IS " + listMessg.et(sizeoflist -1)); 
+0

精彩的回答..謝謝很多朋友。運作良好。我還有一個疑問。我需要獲取個人好友發送的最後一條消息。我怎麼能得到這個。使用上面的代碼,我可以得到在sqlite中插入的最後一個值。同樣的方式,我需要獲得由個人好友發送的最後一個值(消息)。你能幫我解決這個問題嗎?謝謝 – user1265623 2012-03-17 05:35:39

+0

@ user1265623我不知道你是如何處理你的數據庫的用戶,但我可以建議一件事情,如果你有一個用戶ID使它成爲消息表中的列並根據該消息進行查詢並在數組中接收它,最後一個索引將有該用戶的最後一條消息 – 2012-03-19 03:45:13

+0

我不清楚你在說什麼。你可以簡化並告訴我我需要提供的查詢。 – user1265623 2012-03-27 13:38:07

1

SQLiteDatabase返回插入行的ID。你可以記住這個id值並使用它。

long lastId = db.insert(......); 
相關問題