2012-03-16 128 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(......); 
相关问题