Search code examples
iossqlitefmdb

Can't read data using FMDB


I'm using FMDB. I create and insert into table. It works fine.

idx INTEGER NOT NULL DEFAULT 0 PRIMARY KEY AUTOINCREMENT

topicId Varchar NOT NULL

listChat BLOB NOT NULL

enter image description here

But I can't get all data from listChat collumn. Here is my code:

- (NSMutableArray*)readChatHistoryFromDatabaseWithTopicId:(NSString *)topicId {
    NSMutableArray *listChat = [[NSMutableArray alloc] init];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *path = [self databasePath];
    if ([fileManager fileExistsAtPath:path] == YES) {
        FMDatabase *database = [FMDatabase databaseWithPath:path];
        if (database) {
            [database open];
            NSString *query = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE topicId=\"%@\"", OCSDK_CHAT_HISTORY_TABLE_NAME, topicId];
            FMResultSet *results = [database executeQuery:query];
            [results next];
            NSData *notesData = [results dataForColumn:@"listChat"];
            [listChat addObject:notesData];
            NSLog(@"notes: %@", listChat);
        }
        [database close];
    }
    return listChat;
}

It print:

enter image description here

What is wrong with my code?


Solution

  • Change of code:

    - (NSMutableArray*)readChatHistoryFromDatabaseWithTopicId:(NSString *)topicId {
        NSMutableArray *listChat = [[NSMutableArray alloc] init];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *path = [self databasePath];
        if ([fileManager fileExistsAtPath:path] == YES) {
            FMDatabase *database = [FMDatabase databaseWithPath:path];
            if (database) {
                [database open];
                NSString *query = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE topicId=\"%@\"", OCSDK_CHAT_HISTORY_TABLE_NAME, topicId];
                FMResultSet *results = [database executeQuery:query];
                while([results next]) {
    
                  NSString *noteString = [results stringForColumn:@"topicId"]
                  [listChat addObject: noteString];
                  NSLog(@"notes: %@", listChat);
              }
            }
            [database close];
        }
        return listChat;
    }
    

    You are fetching NSData values from database for the key topicId. You need to fetch NSStringvalue instead. Check above code.