为数据库选择创建通用函数

时间:2011-06-04 18:01:25

标签: objective-c sqlite

我正在开发一款iPhone应用程序。我有一个从sqlite数据库读取数据并将结果放入数组的函数。一切正常。以下是填充数组的函数的一部分:

while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
    NSString *aVar1 = [NSString stringWithUTF8String(char*)sqlite3_column_text(compiledStatement, 0)];
    NSString *aVar2 = [NSString stringWithUTF8String(char*)sqlite3_column_text(compiledStatement, 1)];

    NSArray  *anArray = [NSArray arrayWithObjects:aVar1,aVar2,nil];
    [returnArray addObject:anArray]
    [anArray release];
}
//return the array

我想使这个函数更通用,以便它将sql语句字符串作为参数,并返回数组的可变阵列,无论结果集中有多少列。

有办法做到这一点吗?解决方案不必包含数组 - 可以是任何集合对象。我只是想找到一种方法使函数可以重用于同一数据库的其他查询。

2 个答案:

答案 0 :(得分:0)

难道你不能做这样的事情:

int numCols = sqlite3_column_count(compiledStatement);
NSMutableArray *result = [NSMutableArray array];
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
    NSMutableArray *array = [NSMutableArray array];
    for (int i = 0; i < numCols; i++) {
        [array addObject:
         [NSString stringWithUTF8String:
          (char *)sqlite3_column_text(compiledStatement, i)]];
    }
    [result addObject:array];
}

答案 1 :(得分:0)

+(NSArray *)executeQueryAndReturnArray:(NSString *)query {
    sqlite3_stmt *statement = nil;
    const char *sql = [query UTF8String];
    if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) != SQLITE_OK) {
        NSLog(@"[SQLITE] Error when preparing query!");
    } else {
        NSMutableArray *result = [NSMutableArray array];
        while (sqlite3_step(statement) == SQLITE_ROW) {
            NSMutableArray *row = [NSMutableArray array];
            for (int i = 0; i < sqlite3_column_count(statement); i++) {
                int colType = sqlite3_column_type(statement, i);
                id value;
                if (colType == SQLITE_TEXT) {`enter code here`
                    const unsigned char *col = sqlite3_column_text(statement, i);
                    value = [NSString stringWithFormat:@"%s", col];
                } else if (colType == SQLITE_INTEGER) {
                    int col = sqlite3_column_int(statement, i);
                    value = [NSNumber numberWithInt:col];
                } else if (colType == SQLITE_FLOAT) {
                    double col = sqlite3_column_double(statement, i);
                    value = [NSNumber numberWithDouble:col];
                } else if (colType == SQLITE_NULL) {
                    value = [NSNull null];
                } else {
                    NSLog(@"[SQLITE] UNKNOWN DATATYPE");
                }
                [row addObject:value];
            }
            [result addObject:row];
        }
        return result;
    }
    return nil;
}