在iOS中的sqlite中获取数据时遇到问题

时间:2016-11-25 10:27:30

标签: ios objective-c xcode sqlite

- (NSMutableArray*)getAllDataFromTableUSERINFO:(NSString *)fetchQuery {
        NSMutableArray *resultArray1 =[[NSMutableArray alloc]init];
        @autoreleasepool {
        if (sqlite3_open([[self getDBPath]UTF8String],&database)==SQLITE_OK){
            sqlite3_stmt *stmt;
            const char *sqlfetch=[fetchQuery UTF8String];
            if (sqlite3_prepare(database, sqlfetch, -1,&stmt, NULL)==SQLITE_OK) {
                while (sqlite3_step(stmt)==SQLITE_ROW){
                    RM_USER_INFO *UserInfo = [[RM_USER_INFO alloc]init];
                    UserInfo.uid=[NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt,0)];
                    UserInfo.username=[NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt,1)];
                    UserInfo.password=[NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt,2)];
                    UserInfo.fname=[NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt,3)];
                    UserInfo.mname=[NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt,4)];
                    [resultArray1 addObject:UserInfo];
                }
            }
            sqlite3_finalize(stmt);
            stmt=nil;
            sqlite3_close(database);
            sqlite3_release_memory(120);
        }
        }
        return resultArray1;
    }

在几次操作后始终获取EXE_BAD_ACCESS

1 个答案:

答案 0 :(得分:0)

尝试此功能:

static NSInteger DBBUSY;
+(NSMutableArray *)executeQuery:(NSString*)str{
    sqlite3_stmt *statement= nil;
    sqlite3 *database;
    NSString *strPath = Your Database path here;
    while(DBBUSY);
    DBBUSY = 1;
    NSMutableArray *allDataArray = [[NSMutableArray alloc] init];
    if (sqlite3_open([strPath UTF8String],&database) == SQLITE_OK) {
        if (sqlite3_prepare_v2(database, [str UTF8String], -1, &statement, NULL) == SQLITE_OK) {
            while (sqlite3_step(statement) == SQLITE_ROW) {
                NSInteger i = 0;
                NSInteger iColumnCount = sqlite3_column_count(statement);
                NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
                while (i< iColumnCount) {
                    NSString *str = [self encodedString:(const unsigned char*)sqlite3_column_text(statement, i)];
                    NSString *strFieldName = [self encodedString:(const unsigned char*)sqlite3_column_name(statement, i)];
                    if(!str)
                        str = @"";
                    [dict setObject:str forKey:strFieldName];
                    i++;
                }

                [allDataArray addObject:dict];

            }
        }
        DBBUSY = 0;

        sqlite3_finalize(statement);
    } 
    sqlite3_close(database);
    return allDataArray;
}

这可能对你有所帮助:)。