sqlite3逆序分页读取数据

项目中有一个需求:

从本地数据库读取数据,读取方式为分页、逆序;

如下:

- (void)searchDataWithPage:(NSInteger)page andLimit:(NSInteger)limit userName:(NSString *)userName complete:(void(^)(NSArray *searchArray))searchArray;
- (void)searchDataWithPage:(NSInteger)page andLimit:(NSInteger)limit userName:(NSString *)userName complete:(void(^)(NSArray *searchArray))searchArray{
    
    NSMutableArray *array = [NSMutableArray array];
    [self openDataBase];
    NSString *sql = [NSString stringWithFormat:@"select * from MESSAGE_LOCAL where user_name = '%@' order by id desc limit %ld,%ld ",userName,page,limit];
    sqlite3_stmt *stmt = nil;
    sqlite3_prepare(dataBase, sql.UTF8String, -1, &stmt, NULL);
    while (sqlite3_step(stmt) == SQLITE_ROW) {
        MessageModel *msgModel = [[MessageModel alloc] init];
        msgModel.msg_id = [[NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 0)] integerValue];
        msgModel.title = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 1)];
        msgModel.content = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 2)];
        msgModel.webUrl = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 3)];
        msgModel.pictureUrl = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 4)];
        msgModel.sendTime = [[NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 5)] integerValue];;
        
        [array addObject:msgModel];
    }
    if (array && searchArray) {
        searchArray(array);
    }
    //清空临时缓存
    sqlite3_finalize(stmt);
    [self closeDataBase];
}

核心的语句就是下面的sql 语句

NSString *sql = [NSString stringWithFormat:@"select * from MESSAGE_LOCAL where user_name = '%@' order by id desc limit %ld,%ld ",userName,page,limit];

因为每个账号的数据不一样,所以就在表中加了一个user_name字段来区分,获取数据时也就用它来获取对应账号的数据。order by id desc表示逆序。limit %ld,%ld用于分页获取数据。

你可能感兴趣的:(sqlite3逆序分页读取数据)