【发布时间】:2016-09-13 20:16:13
【问题描述】:
我的问题是如何将获取的 JSON 数组数据插入 sqlite 数据库。 我已经获取了 JSON 数据,它是一个字典数组。
我保存 JSON 结果的代码如下所示:
-(BOOL) saveApiResults: (NSString *)tableName : (NSArray *)data
{
BOOL saveSuccess = NO;
@try {
const char *dbPath = [databasePath UTF8String];
if(sqlite3_open(dbPath,&database)==SQLITE_OK) {
sqlite3_exec(database, "BEGIN", 0, 0, 0);
//pass an array containing json dictionary to below line
NSDictionary *rowData=[data objectAtIndex:0];
NSArray *keyArray = [rowData allKeys];
NSLog(@"key array %@",keyArray);
NSString *insertSQL=@"INSERT INTO ";
insertSQL=[insertSQL stringByAppendingString:@"moodsdata"];
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) {
for (NSUInteger i = 0; i < [data count]; i++) {
NSDictionary *rowData=[data objectAtIndex:0];
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];
NSLog(@"values %@",val);
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 saveSuccess;
}
我的问题是,当我尝试将 JSON 数组传递给此方法时,它只会保存第一个数组对象的值。即只保存第一个字典值。请告诉我我做错了什么。
【问题讨论】:
-
请使用与您的问题相关的代码更新您的问题。你都尝试了些什么?您问题中的代码与您的问题无关。
-
不相关,但你为什么要这样构建
CREATE语句?为什么它不是单个字符串文字?至少使用NSMutableString一块一块地构建它。 -
我已经更新了我的问题。请检查一下。
标签: ios arrays json sqlite relational-database