繁体   English   中英

如何将json数组插入并保存到sqlite ios中

[英]how to insert and save json array into sqlite ios

-(BOOL)createDB{
NSString *docsDir;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
databasePath = [[NSString alloc] initWithString:
                [docsDir stringByAppendingPathComponent: @"oiwii.db"]];
BOOL isSuccess = YES;
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
    const char *dbpath = [databasePath UTF8String];
    if (sqlite3_open(dbpath, &database) == SQLITE_OK)
    {
        char *errMsg;
        const char *sql_stmt ="create table if not exists jsonData (status text, message text,  mood_name text, description text, c1 text, c2 text c3 text, c4 text, c5 text, font_name text, font_size text, font_color text)";
        if (sqlite3_exec(database, sql_stmt, NULL, NULL, &errMsg)!= SQLITE_OK)
        {
            isSuccess = NO;
            NSLog(@"Failed to create table");
        }
        sqlite3_close(database);
        return  isSuccess;
    }
    else {
        isSuccess = NO;
        NSLog(@"Failed to open/create database");
    }
}
return isSuccess;

}

我已经在上面创建了一个数据库,我正在尝试将json对象(数组)添加到我的sqlite中。 我的json对象看起来像这样-{“ moods_name”:“ mood2”,“ description”:“这是心情2”,“ c1”:“ D4FF38”,“ c2”:“ FFA83D”,“ c3”:“ FFFA9E” ,“ c4”:“ 66FFBA”,“ c5”:“ 63FFE8”,“ font_name”:“默认”,“ font_size”:“ 10”,“ font_color”:“ 363636”},我想获取此数组

-(BOOL)saveData:(NSString *)status message:(NSString *)message mood_name:(NSString *)mood_name description:(NSString *)description c1:(NSString *)c1 c2:(NSString *)c2 c3:(NSString *)c3 c4:(NSString *)c4 c5:(NSString *)c5 font_name:(NSString *)font_name font_size:(NSString *)font_size font_color:(NSString *)font_color{

const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
    NSString *insertSQL = [NSString stringWithFormat:@"insert into jsonData (status,message, description, c1,c2,c3,c4,c5,font_name,font_size,font_color) values (\"%@\",\"%@\", \"%@\", \"%@\",\"%@\",\"%@\",\"%@\",\"%@\",\"%@\",\"%@\",\"%@\")",status, message, description, c1,c2,c3,c4,c5,font_name,font_size,font_color];
    const char *insert_stmt = [insertSQL UTF8String];
    sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL);
    if (sqlite3_step(statement) == SQLITE_DONE)
    { NSLog(@"data saved");
        return YES;

    }
    else {
        return NO;
    }

}

sqlite3_reset(statement);
return NO;

}

更新:获取数据的代码

-(void)fetchdata
{
arrayfetched = [[NSMutableArray alloc] init];

// Setup the database object
sqlite3 *database;

// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{

    //SQLIte Statement
    NSString *sqlStatement_userInfo =[NSString stringWithFormat:@"Select * from moodsdata"];

    sqlite3_stmt *compiledStatement;


    if(sqlite3_prepare_v2(database, [sqlStatement_userInfo UTF8String], -1, &compiledStatement, NULL) == SQLITE_OK)
    {

        // Loop through the results and add them to the fetchedarray
        while(sqlite3_step(compiledStatement) == SQLITE_ROW)
        {
            // Init the Data Dictionary
            NSMutableDictionary *_dataDictionary=[[NSMutableDictionary alloc] init];

            NSString *msg = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];

            NSString *status = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];

            NSString *data = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];

            [_dataDictionary setObject:[NSString stringWithFormat:@"%@",msg] forKey:@"message"];
            [_dataDictionary setObject:[NSString stringWithFormat:@"%@",status] forKey:@"status"];
            [_dataDictionary setObject:[NSString stringWithFormat:@"%@",data] forKey:@"data"];

            [arrayfetched addObject:_dataDictionary];
            NSLog(@"array fetched%@",arrayfetched);

        }
    }
    else
    {
        NSLog(@"No Data Found");
    }

    // Release the compiled statement from memory
    sqlite3_finalize(compiledStatement);
}
   sqlite3_close(database);
NSLog(@" fetched array%@",arrayfetched);
}

请帮我。

您可以创建一个类,在其中完成所有与数据库相关的工作。 从该类中调用该特定方法,即可在项目中的任何位置插入,更新或删除数据库中的任何内容。

您可以参考以下链接了解更多信息和教程:

尝试使用此方法保存到数据库。 准备的语句要比普通插入查询好。

-(BOOL) saveApiResults: (NSString *)tableName : (NSArray *)data {
    //assign false value to saveSuccess
    BOOL saveSuccess = NO;

    sqlite3 *database;
    @try {
        //get database path
        const char *dbPath = [YOUR_DB_PATH UTF8String];
        if(sqlite3_open(dbPath,&database)==SQLITE_OK) {

            sqlite3_exec(database, "BEGIN", 0, 0, 0);

            NSDictionary *rowData=[data objectAtIndex:0];
            //convert the string into array
            NSArray *keyArray = [rowData allKeys];

            NSString *insertSQL=@"INSERT OR REPLACE INTO ";
            insertSQL=[insertSQL stringByAppendingString:tableName];
            insertSQL=[insertSQL stringByAppendingString:@" VALUES("];
            for(int j=0;j<[keyArray count];j++)
            {
                insertSQL=[insertSQL stringByAppendingString:@"?"];
                if(j<[keyArray count]-1)
                    insertSQL=[insertSQL stringByAppendingString:@","];
            }
            insertSQL=[insertSQL stringByAppendingString:@");"];


            NSLog(@"query : %@ ",insertSQL);

            const char *sqlstatement = [insertSQL UTF8String];

            sqlite3_stmt *compiledstatement;

            if(sqlite3_prepare_v2(database,sqlstatement , -1, &compiledstatement, NULL)==SQLITE_OK) {

                //fetch the dictionary(key,value) from the array of api result
                for (NSUInteger i = 0; i < [data count]; i++) {
                    NSDictionary *rowData=[data objectAtIndex:i];

                    //get the value for ech key from api response and execute the insert statement
                    for(int j=0;j<[keyArray count];j++) {
                        NSString *val = @"";
                        NSString *value=(NSString *)[rowData objectForKey:[keyArray objectAtIndex:j]];
                        if((value != nil) && (![value isEqual:[NSNull null]]))
                            val=[NSString stringWithFormat:@"%@",value];

                        sqlite3_bind_text(compiledstatement,j+1,[val UTF8String], -1, SQLITE_TRANSIENT);
                    }

                    if(sqlite3_step(compiledstatement) != SQLITE_DONE) {
                        NSLog(@"ERROR");
                    }

                    sqlite3_clear_bindings(compiledstatement);
                    sqlite3_reset(compiledstatement);


                }

                sqlite3_exec(database, "COMMIT", 0, 0, 0);
                saveSuccess = YES;
                 NSLog(@"RESULTS SAVED SUCCESSFULLY!");
            } else {
                NSLog(@"Statement FAILED (%s)", sqlite3_errmsg(database));
            }

            sqlite3_finalize(compiledstatement);

        } else {
                NSLog(@"Statement FAILED (%s)", sqlite3_errmsg(database));
        }
    }
    @catch (NSException *exception) {
        NSLog(@"NSException : %@",exception.description);
    }
    @finally {
        sqlite3_close(database);
    }

    //return data save status
    return saveSuccess;
}

然后在这里解析您的JSON响应,并将NSDictionary对象的NSArray发送到saveApiResults方法。

-(void) saveJSONData {
    NSData* jsonData = [YOUR_JSON_RESPONSE dataUsingEncoding:NSUTF8StringEncoding];

    NSError *error = nil;
    NSDictionary *responseObj = [NSJSONSerialization
                                 JSONObjectWithData:jsonData
                                 options:0
                                 error:&error];

    if(! error) {
        NSArray *responseArray = [responseObj objectForKey:@"data"];

        [self saveApiResults : YOUR_TABLE_NAME : responseArray];
    } else {
        NSLog(@"Error in parsing JSON");
    }
}

//获取结果的代码

-(NSMutableArray *)getQueryResult {

    //get the database path
    const char *dbpath = [databasePath UTF8String];

    sqlite3 *DB;
    NSMutableArray *results=[[NSMutableArray alloc] init];

    @try {
        sqlite3_stmt *statement;
        NSMutableDictionary *dict;

        if (sqlite3_open(dbpath, &DB) == SQLITE_OK) {

            //sql select query
            NSString *querySQL = [NSString stringWithFormat: @"SELECT * from moodsdata"];

            const char *query_stmt = [querySQL UTF8String];

            if (sqlite3_prepare_v2(DB, query_stmt, -1, &statement, NULL) == SQLITE_OK){

                if(sqlite3_step(statement) == SQLITE_ROW) {
                    do {
                        dict = [[NSMutableDictionary alloc] init];

                        const unsigned char *msg = sqlite3_column_text(statement, 0);

                        const unsigned char *status = sqlite3_column_text(statement, 1);

                        const unsigned char *data = sqlite3_column_text(statement, 2);

                        [dict setValue:[NSString stringWithFormat:@"%s",msg] forKey:@"message"];
                        [dict setValue:[NSString stringWithFormat:@"%s",status] forKey:@"status"];
                        [dict setValue:[NSString stringWithFormat:@"%s",data] forKey:@"data"];

                        //add dictionary(key,value) to the array
                        [results addObject:dict];
                    }

                    while (sqlite3_step(statement) == SQLITE_ROW);
                } else {
                    NSLog(@"Statement FAILED (%s)",sqlite3_errmsg(DB));
                }

            } else {
                NSLog(@"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(DB));
            }

            sqlite3_finalize(statement);
        } else {
            NSLog(@"Can not open DB : %s",sqlite3_errmsg(DB));
        }

    }
    @catch (NSException *exception) {
        NSLog(@"NSException : %@",exception.description);
    }
    @finally {
        sqlite3_close(DB);
    }

    //return the database results
    return results;
}

//如何使用getQueryResults中的结果

-(void) showData {
    NSMutableArray *results = [self getQueryResult];
    for (NSMutableDictionary *resultDic in results) {
        NSString *msg = [resultDic objectForKey:@"message"];
        NSString *status = [resultDic objectForKey:@"status"];
        NSString *data = [resultDic objectForKey:@"data"];

        NSLog(@"Result : %@ : %@ : %@",msg,status,data);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM