【问题标题】:SQLite Insert Multiple rows from JSON object iosSQLite从JSON对象ios插入多行
【发布时间】:2020-02-24 10:10:55
【问题描述】:

我正在使用 NSURLSession 类通过 http 获取 json 数据

    NSString *url = @"http://10.0.0.25/Website/database.php";

NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:url] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    dispatch_async(dispatch_get_main_queue(), ^{ 
        NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"String Output: %@",str);


    });
}];
[task resume];

我得到以下示例输出:

{ "client_id":"12", "finger_print_code":"", “national_id”:“28811982” }, { "client_id":"32", "finger_print_code":"", “national_id”:“293239323” }

我想从 JSON 字符串或对象中获取上述数据到我的 SQLite 数据库中。有人建议FMDB,但我不太熟悉。

  query = [NSString stringWithFormat:@"insert into clientInfo values(null, %d, %d, '%@')", [importedID intValue], [nationalID intValue], fingerPrintCode];

这是insert multiple data 的方法,但我想学习如何从 JSON 中插入数据,并一次或同时插入。 Here 是示例之一,但事实证明它没有帮助。

【问题讨论】:

    标签: ios objective-c json sqlite fmdb


    【解决方案1】:

    假设样本数据实际上是一个 JSON 数组

    [{ "client_id":"12", "finger_print_code":"", "national_id":"28811982" },
     { "client_id":"32", "finger_print_code":"", "national_id":"293239323" }]
    

    并且您使用的 sqlite 版本启用了JSON1 扩展,您可以执行类似的操作

    INSERT INTO clientInfo(client_id, finger_print_code, national_id)
    SELECT json_extract(j.value, '$.client_id')
         , json_extract(j.value, '$.finger_print_code')
         , json_extract(j.value, '$.national_id')
    FROM json_each(?) AS j;
    

    您将保存 JSON 数组的字符串绑定到从上述查询创建的准备好的语句中的参数。根据需要调整列名(因为我猜你没有给出表定义)。

    【讨论】:

    • 您好,j 到底是什么,JSON 数组在哪里?谢谢
    • @bots_developer_fix 这只是json_each() 返回的行的别名。有关详细信息,请参阅链接的文档。如果您从未见过 AS 或不知道别名是什么,或者是基本的 sql 教程。
    【解决方案2】:

    感谢您的回答。这就是我在 Objective-c 中实现它的方式,以防有人想知道如何实现。在这种情况下,我使用自定义数据库类与我的 SQLite 数据库进行通信。

            NSString *queryInsert;
        queryInsert = [NSString stringWithFormat:@"INSERT INTO clientInfo(clientID, nationalID, fingerPrintCode) SELECT json_extract(j.value, '$.client_id') , json_extract(j.value, '$.national_id') , json_extract(j.value, '$.finger_print_code')  FROM json_each('%@') AS j", my_json_array];
        [self.dbManager executeQuery:queryInsert];
    

    my_json_array 正是我从服务器获取的 jsonArray 数据。我对JSON1 扩展了解不多,感谢您的帮助和分享知识。

    【讨论】:

      猜你喜欢
      • 2016-01-18
      • 2019-02-25
      • 2017-12-16
      • 1970-01-01
      • 2012-05-22
      • 2014-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多