【问题标题】:Make arrays from json and save arrays in columns of SQLite in objective C iOS从json制作数组并将数组保存在objective C iOS中的SQLite列中
【发布时间】:2018-09-04 05:38:55
【问题描述】:

我正在从我的json file 中检索数据,其中包含timingssunrisesunsetmidnight。我想做array for sunrisearray for sunsetarray for midnight。并将我的数组保存在 SQLite 中的 sunriseColumnsunsetColumnmidnightColumn 中。

但我有点困惑如何以正确的方式做到这一点。

我的 ViewDidLoad() 中有什么

- (void)viewDidLoad {
[super viewDidLoad];

[self saveinDatabase];

NSURL *url = [NSURL fileURLWithPath:@"/Users/macbook/Desktop/Test/Test/myFile.json"];
NSString *fileContent = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSLog(@"Json data is here %@", fileContent);

在字典中保存数据

NSArray *data = [[theFeedString JSONValue] objectForKey:@"data"];
for (NSDictionray *dict in data) {
NSString *timings = [[dict objectForKey:@"timings"] intValue];
NSArray *sunriseArray = [objectForKey:@"sunrise"]
NSArray *sunsetArray = [objectForKey:@"sunset"]
NSArray *midnight = [objectForKey:@"midnight"]
}

在我的控制台中,我从我的 json 中获取所有数据,我的 json 看起来像这样

{
"data": [
{
"timings": {
"Sunrise": "07:14 (PKT)",
"Sunset": "18:15 (PKT)",
"Midnight": "00:45 (PKT)"
}
},
{
"timings": {
"Sunrise": "07:13 (PKT)",
"Sunset": "06:40 (PKT)",
"Midnight": "00:45 (PKT)"
}
}
]
}

一种在SQLite中存储数据的方法

-(void) saveinDatabase {

NSString *docsDir;
NSArray *dirPaths;

dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, TRUE);
docsDir = dirPaths[0];

_dbPath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:@"mydatabase.db"]];
NSFileManager *fileManager = [NSFileManager defaultManager];
if([fileManager fileExistsAtPath:_dbPath] == NO) {

    const char *dbPathagain = [_dbPath UTF8String];

    if(sqlite3_open(dbPathagain, &_DB) == SQLITE_OK ) {
        char *errorMessage;
        const char *sql_statement = "CREATE TABLE IF NOT EXISTS jsontable(ID integer primary key, sunrise text, sunset text, midnight text)";

        NSLog(@"created table success");

        sqlite3_stmt *statement;
        const char *dbPathagain = [ _dbPath UTF8String];

        if(sqlite3_open(dbPathagain, &_DB) == SQLITE_OK ) {
            NSString *insertSQLData = [NSString stringWithFormat:@"INSERT INTO jsontable(sunrise, sunset, midnight) VALUES (\"%@\", \"%@\", \"%@\")", sunriseArray, sunsetArray, midnightArray];
            const char *insert_statement = [insertSQLData UTF8String];
            sqlite3_prepare_v2(_DB, insert_statement, -1, &statement, NULL);

            if (sqlite3_step(statement) == SQLITE_DONE) {
                NSLog(@"data added successfully");
                NSLog(@"here is sunrise times %@", sunriseArray);
            }
            else {
                NSLog(@"could not add timings");
            }
            sqlite3_finalize(statement);
            sqlite3_close(_DB);
        }

        if (sqlite3_exec(_DB, sql_statement, NULL, NULL, &errorMessage) != SQLITE_OK) {
            NSLog(@"failed to create table");
        }
        sqlite3_close(_DB);
    }
    else {
        NSLog(@"failed to open db or cretate table");
    }
}
}
}

【问题讨论】:

  • 此代码会将所有 3 个数组保存在单行中。你真的想实现这个目标吗?
  • 我可以运行循环,以便将三个数组中的一项一项添加到一行中
  • 如果要将单个数据存储在单行中,则无需创建单独的数组。只需循环到名为“data”的数组并获取每个字典并将其存储在数据库中
  • 你能帮我解答一下吗
  • 你能告诉我为什么你应该想要 3 个不同的数组吗?您在哪里遇到问题?

标签: ios objective-c sqlite nsarray nsdictionary


【解决方案1】:

在您的代码中进行以下更改:

将您的“数据”数组传递给方法。

 NSDictionary *dict = @{
                               @"data": @[
                                       @{
                                           @"timings": @{
                                                   @"Sunrise": @"07:14 (PKT)",
                                                   @"Sunset": @"18:15 (PKT)",
                                                   @"Midnight": @"00:45 (PKT)"
                                                   }
                                           },
                                       @{
                                           @"timings": @{
                                                   @"Sunrise": @"07:13 (PKT)",
                                                   @"Sunset": @"06:40 (PKT)",
                                                   @"Midnight": @"00:45 (PKT)"
                                                   }
                                           }
                                       ]
                               };
     NSArray *arrData = [NSArray arrayWithArray:[dict objectForKey:@"data"]];
    [self saveinDatabase:arrData];

用以下代码替换方法:

-(void) saveinDatabase:(NSArray*) arrData {

    NSString *docsDir;
    NSArray *dirPaths;

    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, TRUE);
    docsDir = dirPaths[0];

    _dbPath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:@"mydatabase.db"]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if([fileManager fileExistsAtPath:_dbPath] == NO) {

        const char *dbPathagain = [_dbPath UTF8String];

        if(sqlite3_open(dbPathagain, &_DB) == SQLITE_OK ) {
            char *errorMessage;
            const char *sql_statement = "CREATE TABLE IF NOT EXISTS jsontable(ID integer primary key, sunrise text, sunset text, midnight text)";

            NSLog(@"created table success");

            sqlite3_stmt *statement;
            const char *dbPathagain = [ _dbPath UTF8String];

            if(sqlite3_open(dbPathagain, &_DB) == SQLITE_OK ) {


                for (int i=0; i<arrData.count; i++) {

                    NSDictionary *dictTiming = [[arrData objectAtIndex:i] valueForKey:@"timings"];
                    NSString *insertSQLData = [NSString stringWithFormat:@"INSERT INTO jsontable(sunrise, sunset, midnight) VALUES (\"%@\", \"%@\", \"%@\")", [dictTiming objectForKey:@"Sunrise"], [dictTiming objectForKey:@"Sunset"], [dictTiming objectForKey:@"Midnight"]];
                    const char *insert_statement = [insertSQLData UTF8String];
                    sqlite3_prepare_v2(_DB, insert_statement, -1, &statement, NULL);

                    if (sqlite3_step(statement) == SQLITE_DONE) {
                        NSLog(@"data added successfully");
                        NSLog(@"here is sunrise times %@", sunriseArray);
                    }
                    else {
                        NSLog(@"could not add timings");
                    }

                }


                sqlite3_finalize(statement);
                sqlite3_close(_DB);
            }

            if (sqlite3_exec(_DB, sql_statement, NULL, NULL, &errorMessage) != SQLITE_OK) {
                NSLog(@"failed to create table");
            }
            sqlite3_close(_DB);
        }
        else {
            NSLog(@"failed to open db or cretate table");
        }
    }
}

【讨论】:

  • 感谢您的努力,但出现 Ann 错误“无法打开 db 或创建表
  • 出现的确切错误是什么? “未能打开数据库或创建表”是您记录的错误消息。你能分享系统提供的错误信息吗
  • 2018-03-26 12:55:25.690625+0500 Test[1260:91590] failed to open db or cretate table 2018-03-26 12:55:25.700825+0500 Test[1260:91590] Json data is here { "data": [ { "timings": {
  • // Open the test.db file rc = sqlite3_open("test.db", &amp;db); // &lt;-- creates DB if not found ?? if( rc ){ // failed NSLog(stderr, @"ERROR: Can't open database: %s\n", sqlite3_errmsg(db)); } 使用此代码查看系统提供的错误
  • 这个方法给我错误请你在回答中更新这个PLZ
猜你喜欢
  • 2016-09-01
  • 2016-08-30
  • 1970-01-01
  • 2012-11-11
  • 2016-09-13
  • 1970-01-01
  • 1970-01-01
  • 2011-07-01
  • 1970-01-01
相关资源
最近更新 更多