【发布时间】:2014-04-28 13:32:44
【问题描述】:
我有一个 "messages table",我只想用他的最后一条消息检索 "user ID"。
我尝试在彼此之间添加“2条sql语句”,但它一直在不停地循环,
sqlite3_stmt *statement;
NSMutableArray * messages = [[NSMutableArray alloc]init];
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_chatDB) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:
@"SELECT DISTINCT FROMID , USERNAME from CHATCOMPLETE"];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(_chatDB,
query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW)
{
int userID = [[[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 0)] integerValue];
NSString *querySQL2 = [NSString stringWithFormat:
@"SELECT MESSAGE , USERNAME from CHATCOMPLETE where FROMID=\"%d\"",userID];
const char *query_stmt2 = [querySQL2 UTF8String];
if (sqlite3_prepare_v2(_chatDB,
query_stmt2, -1, &statement, NULL) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW)
{
NSLog(@"LAST MESSAGE %@",[[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 0)]);
sqlite3_reset(statement);
}
}
}
sqlite3_reset(statement);
}
}
return messages;
更新: 这是插入消息
-(void)saveData:(NSString *)message toID:(int)toID fromID:(int)fromID isRead:(BOOL)read date:(NSDate *)date messageID:(int)messageID userName:(NSString*)userName
{
sqlite3_stmt *statement;
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_chatDB) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO CHATCOMPLETE (MESSAGE, TOID, FROMID, READ, date, MESSAGEID, USERNAME) VALUES (\"%@\", \"%d\", \"%d\", \"%c\", \"%@\", \"%d\", \"%@\")", message, toID, fromID, read, date,messageID,userName];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(_chatDB, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(@"DONE");
/* status.text = @"Contact added";
name.text = @"";
address.text = @"";
phone.text = @"";*/
} else {
// status.text = @"Failed to add contact";
}
sqlite3_finalize(statement);
sqlite3_close(_chatDB);
}
}
【问题讨论】:
-
我有一个聊天表,它有“ID 作为主键”、fromID、TOID、Message,我想获取 fromID 发送的最后一条消息。
-
任何日期/时间列?如果没有,如何找到“最后一条消息”?
-
只需在 while 循环外打印 NSLog(@"LAST MESSAGE %@",[[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text(statement, 0)])
-
总是在循环之外只显示最后一个值\
-
@trojanfoe 我不能用 messageID 降序排列它们吗?