从iOS中的SQL表中获取特定行?

时间:2012-12-18 12:16:35

标签: ios database sqlite

我使用SQLite Manager(firefox插件)创建了一个包含4列5行的表。 现在我想借助以下代码从该表中获取整个随机行,但它不起作用,因为我之前从未使用过它..我可能做错了什么?

-(NSDictionary *)fetchQuestionsWithRowID:(NSInteger)rowID withDbPath:(NSString *)dbPath
        {

      NSDictionary *questDic=[NSDictionary dictionary];
            sqlite3 *database=nil;
            if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
            {
                const char *sql = "SELECT * FROM quizQuestions Where rowid=?";

                sqlite3_stmt *selectstmt;

                int result = sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL);

                if(result != SQLITE_OK) {
                    NSLog(@"Prepare-error #%i: %s", result, sqlite3_errmsg(database));
                }

                if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK)
                {
// confused here
                    sqlite3_bind_text16(selectstmt, 1, &rowID, -1, SQLITE_TRANSIENT);
                    while(sqlite3_step(selectstmt) == SQLITE_ROW) {

                        NSString *str = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)];

                        NSLog(@"string is %@",str);

                    }
                }
            }
            sqlite3_close(database);
            return questDic;
        }

1 个答案:

答案 0 :(得分:0)

Hemant,看下面的代码可能会有所帮助但你需要根据你的需要制作代码,意味着需要更正表格等:

 NSString* sqliteQuery = NULL;
    sqliteQuery = [NSString stringWithFormat:@"SELECT roomImage,bookID,roomName,floorID,roomDesc,id FROM roomTbl"];
    sqlite3_stmt* statement;
    if( sqlite3_prepare_v2(db, [sqliteQuery UTF8String], -1, &statement, NULL) == SQLITE_OK )
    {
        while( sqlite3_step(statement) == SQLITE_ROW )
        {
            NSMutableDictionary* dict = [NSMutableDictionary new];
            NSData* data = nil;
            int length = sqlite3_column_bytes(statement, 0);
            data       = [NSData dataWithBytes:sqlite3_column_blob(statement, 0) length:length];
            [dict setObject:[Base64 encode:data] forKey:@"imageFloorBytes"];
            int idFR = sqlite3_column_int(statement, 1);
            [dict setObject:[NSString stringWithFormat:@"%d",idFR] forKey:@"BookingID"];

            [dict setObject:[NSString stringWithFormat:@"%s",(const char*)sqlite3_column_text(statement, 2)] forKey:@"roomName"];
            [dict setObject:[NSString stringWithFormat:@"%d",sqlite3_column_int(statement, 3)] forKey:@"floorID"];
            [dict setObject:[NSString stringWithFormat:@"%s",(const char*)sqlite3_column_text(statement, 4)] forKey:@"roomDesc"];
            [dict setObject:[NSString stringWithFormat:@"%d",sqlite3_column_int(statement, 5)] forKey:@"roomID"];
            [arr addObject:dict];
            [dict release];
        }
    }
    // Finalize and close database.
    sqlite3_finalize(statement);

另外,你导入你的数据库了吗?而且,在执行任何操作之前,还必须检查以下文件或数据库是否存在。

希望,它能解决你的问题