1

我是 iphone 开发的新手。我想在表 sqlite 的行中存储一个 NSDictionary。我用谷歌搜索并找到了很多结果,但它对我不起作用。

这是我的字典:

NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:@"24",@"id",@"Folder",@"name",@"300 MB",@"size", nil];

我也在这个网站上搜索过,但我不明白类似帖子中的任何内容。请向我解释更多关于在表 SQLite DB 行中添加(存储)NSDictionary 的信息。

4

4 回答 4

3

您可以通过创建一个包含三列的表来做到这一点(使用创建表查询)。然后将这些对象从字典中插入这些列(使用插入查询)。

编辑:对于插入数据使用查询:

            NSString *query = [NSString stringWithFormat:@"insert into tablename (column1, column2,column3) values('%@','%@','%@')",[dic objectForKey:@"id"],[dic objectForKey:@"name"],[dic objectForKey:@"size"]];
            NSLog(@"query : %@",query);
            [self executeQuery:query];

在 .h 类中创建一个 sqlite 实例:

sqlite3 *database; and import:  #import<sqlite3.h>

在 .m 类中添加这些方法:

-(NSString *) dataFilePath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSLog(@"PATH %@",[documentsDirectory stringByAppendingPathComponent:DatabaseName]);
    return [documentsDirectory stringByAppendingPathComponent:DatabaseName];
}

/*==================================================================
              METHOD FOR INSERTING DATA IN DATABASE
 ==================================================================*/
-(void)executeQuery:(NSString *)query
{
    //NSLog(@"QUERY : %@",query);

    sqlite3_stmt *statement;
    if(sqlite3_open([[self dataFilePath] UTF8String], &database) == SQLITE_OK)
    {
        if (sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, NULL) == SQLITE_OK)
        {
            if (sqlite3_step(statement) != SQLITE_DONE)
            {
                sqlite3_finalize(statement);
            }
        }
        else
        {
            NSLog(@"query Statement Not Compiled");
        }

        sqlite3_finalize(statement);
        sqlite3_close(database);
    }
    else
    {
        NSLog(@"Data not Opened");
    }
}

对于读取数据:

/*==================================================================
 METHOD FOR Fetching Data FROM DATABASE
 ==================================================================*/
 NSString *query = [NSString stringWithFormat:@"select * from table_name"];
NSMutableArray *tableData = [self fetchingDataFromTable:query];

// 这里表数据数组包含所有记录

-(NSMutableArray *)fetchingDataFromTable:(NSString *)query;
{
    NSLog(@"QUERY : %@",query);

    NSString *idToReturn=@"";
    NSMutableArray *returnArray = [NSMutableArray new];
    if(sqlite3_open([[self dataFilePath] UTF8String], &database) == SQLITE_OK)
    {
        sqlite3_stmt *statement;
        if (sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil)==SQLITE_OK)
        {
            while(sqlite3_step(statement)==SQLITE_ROW)
            {
                NSMutableDictionary *temp= [NSMutableDictionary new];
                const char *s;


                s=(char *)sqlite3_column_text(statement, 0);
                if(s==NULL)
                {
                    idToReturn=@"";
                }
                else
                {
                    idToReturn =[NSString stringWithUTF8String:s];
                }
                [temp setObject:idToReturn forKey:@"id"];

                s=(char *)sqlite3_column_text(statement, 1);
                if(s==NULL)
                {
                    idToReturn=@"";
                }
                else
                {
                    idToReturn =[NSString stringWithUTF8String:s];
                }
                [temp setObject:idToReturn forKey:@"name"];

                s=(char *)sqlite3_column_text(statement, 2);
                if(s==NULL)
                {
                    idToReturn=@"";
                }
                else
                {
                    idToReturn =[NSString stringWithUTF8String:s];
                }
                [temp setObject:idToReturn forKey:@"size"];

                if (temp != nil)
                {
                    [returnArray addObject:temp];

                    temp = nil;
                }

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

}

希望它可以帮助你。

于 2013-05-01T07:07:39.353 回答
0
- (NSMutableDictionary *)executeQuery:(NSString *)query
{
        sqlite3_stmt *stmt;
        const char *tail;
        sqlite3_prepare_v2(db, [query UTF8String], -1, &stmt, &tail);
        if (stmt == NULL)
                return nil;

        int status;
        int num_cols;
        int i;
        int j = 1;
        int type;
        id obj;
        NSString *key;
        NSMutableArray *result;
        NSMutableDictionary *row,*roww;
        j = 0;
        result = [NSMutableArray array];
      roww = [NSMutableDictionary dictionary];
        while ((status = sqlite3_step(stmt)) != SQLITE_DONE) {

                if (status != SQLITE_ROW)
                {

                        continue;
                }
                else
                {
                row = [NSMutableDictionary dictionary];
                num_cols = sqlite3_data_count(stmt);
                for (i = 0; i < num_cols; i++) {
                        obj = nil;
                        type = sqlite3_column_type(stmt, i);
                        switch (type) {
                        case SQLITE_INTEGER:
                                obj = [NSNumber numberWithLongLong:sqlite3_column_int64(stmt, i)];
                                break;
                        case SQLITE_FLOAT:
                                obj = [NSNumber numberWithDouble:sqlite3_column_double(stmt, i)];
                                break;
                        case SQLITE_TEXT:
                                obj = [NSString stringWithUTF8String:sqlite3_column_text(stmt, i)];
                                break;
                        case SQLITE_BLOB:
                                obj = [NSData dataWithBytes:sqlite3_column_blob(stmt, i)
                                    length:sqlite3_column_bytes(stmt, i)];
                                break;
                        case SQLITE_NULL:
                                obj = [NSNull null];
                                break;
                        default:
                                break;
                        }

                        key = [NSString stringWithUTF8String:sqlite3_column_name(stmt, i)];
                        [row setObject:obj forKey:key];
                }

            NSString *keyq = [NSString stringWithFormat:@"%d",j];
            [roww setObject:row forKey:keyq];
            j++;
                    [roww setValue:@"1" forKey:@"Success"];

        }

        }
    sqlite3_finalize(stmt);

   // NSLog(@"%@",roww);
    return roww;
}
于 2016-04-20T03:42:01.233 回答
0

并从 iOS 中的表中获取数据到字典中:

-(void)getData:(NSString *) tablename
{
    NSMutableDictionary * tabledata= [[NSMutableDictionary alloc] init];
    NSString *str = @"select * from ";
    NSString *strQuery = [str stringByAppendingString:tablename];
    tabledata = [db executeQuery:strQuery];

    NSDictionary *dic = [tabledata valueForKey:@"0"];
    NSLog(@"dic is:%@",dic);
}
于 2016-04-20T03:46:43.007 回答
0

我创建了动态代码,它将返回所有行的所有列的列表

 -(NSMutableDictionary*)getRowsFromTableName:(NSString*)tableName
 {
 NSString *databasePath =[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
//                         stringByAppendingPathComponent: @"sqlcipher.db"];
 sqlite3 *db;
 bool sqlcipher_valid = NO;
 NSMutableDictionary *dbData = [[NSMutableDictionary alloc]init];
 NSMutableArray *columnList = [[NSMutableArray alloc]init];

 if (sqlite3_open([databasePath UTF8String], &db) == SQLITE_OK) {
    const char* key = [keyString UTF8String];
    sqlite3_key(db, key, strlen(key));
    if (sqlite3_exec(db, (const char*) "SELECT count(*) FROM sqlite_master;", NULL, NULL, NULL) == SQLITE_OK) {
        if(sqlite3_prepare_v2(db, "PRAGMA cipher_version;", -1, &stmt, NULL) == SQLITE_OK) {
            if(sqlite3_step(stmt)== SQLITE_ROW) {
                const unsigned char *ver = sqlite3_column_text(stmt, 0);
                if(ver != NULL) {
                    sqlcipher_valid = YES;

                    // password is correct (or database initialize), and verified to be using sqlcipher
                    char *errMsg;
                    const char *query = [[NSString stringWithFormat:@"select * from %@",tableName] UTF8String]; //where name = 'abc'";
                    if (sqlite3_exec(db, query, NULL, NULL, &errMsg)
                        != SQLITE_OK)
                    {
                        // isSuccess = NO;
                        NSLog(@"Failed to open data into table");
                        [dbData setValue:@"Failed to open data into table" forKey:@"Message"];
                        [dbData setValue:@"Failed" forKey:@"status"];
                        return dbData;
                    }
                    else
                    {
                        NSLog(@"Data open Successfully");
                        int num_cols;
                        if(sqlite3_prepare_v2(db, query, -1, &stmt, NULL) == SQLITE_OK) {

                            while (sqlite3_step(stmt) == SQLITE_ROW)
                            {
                                num_cols = sqlite3_data_count(stmt);
                                NSMutableDictionary *columnDic = [[NSMutableDictionary alloc]init];
                                for (int i = 1; i < num_cols; i++) {
                                    NSString *colValue = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, i)];
                                    NSString *colName = [NSString stringWithUTF8String:(char*)sqlite3_column_name(stmt, i)];
                                    [columnDic setValue:colValue forKey:colName];
                                    NSLog(@"%@",columnDic);
                                }
                                [columnList addObject:columnDic];
                                columnDic = nil;
                            }
                            NSLog(@"%@",columnList);
                            [dbData setValue:columnList forKey:@"data"];

                        }
                    }
                }
            }
            else
            {
                NSLog(@"Error while binding variable. '%s'", sqlite3_errmsg(db));
                [dbData setValue:[NSString stringWithFormat:@"Error while binding variable. '%s'", sqlite3_errmsg(db)] forKey:@"Message"];
                [dbData setValue:@"Failed" forKey:@"status"];
                return dbData;
            }
            sqlite3_finalize(stmt);
        }
        else
        {
            NSLog(@"Error while creating update statement. '%s'", sqlite3_errmsg(db));
            [dbData setValue:[NSString stringWithFormat:@"Error while creating update statement. '%s'", sqlite3_errmsg(db)] forKey:@"Message"];
            [dbData setValue:@"Failed" forKey:@"status"];
            return dbData;
        }
    }
    else
    {
        NSLog(@"Error while creating update statement. '%s'", sqlite3_errmsg(db));
        [dbData setValue:[NSString stringWithFormat:@"Error while creating update statement. '%s'", sqlite3_errmsg(db)] forKey:@"Message"];
        [dbData setValue:@"Failed" forKey:@"status"];
        return dbData;
    }
    sqlite3_close(db);
}
NSLog(@"%@",dbData);

return dbData;

}

于 2017-07-15T12:03:57.873 回答