【问题标题】:how to store in sqlite database from json如何从json存储在sqlite数据库中
【发布时间】:2013-04-22 21:07:38
【问题描述】:

我创建了一个应用程序,我从 JSON 中读取了 table View 中的许多数据,我想解析这个 JSON 并存储在 sqlite 中,但我不知道我应该从哪里开始?

这是解析我的 json 代码:

@implementation TableViewController
{
    NSArray *news;
    NSMutableData *data;
    NSString *title;
    NSMutableArray *all;
}
@synthesize mainTable;
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"News";
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    NSURL *url = [NSURL URLWithString:@"http://zacandcatie.com/YouTube/json.php"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLConnection *con = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [con start];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    data = [[NSMutableData alloc]init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
    [data appendData:theData];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

    news = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    for (int i =0; i < [news count]; i++)
    {
    NSIndexPath *indexPath = [self.mainTable indexPathForSelectedRow];
    title =[[news objectAtIndex:indexPath.row+i]objectForKey:@"title"];
        if (!all) {
            all = [NSMutableArray array];
        }
        [all addObject:title];
    }
    NSLog(@"%@",all);

    [mainTable reloadData];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    UIAlertView *errorView = [[UIAlertView alloc]initWithTitle:@"Error" message:@"The Connection has been LOST" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [errorView show];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

你是我的 json 网址。我想在 sqlite 中存储“title”和“date_string”值。 请指导我!!!

【问题讨论】:

  • 你可以用字典代替sqlite db
  • 好的,我知道,但我不知道我在做什么?
  • 我不知道如何在sqlite的表中存储字典!!!
  • 这里回答了“[我们如何将数据存储到 NSDictionary?][1]”[1] 的问题:stackoverflow.com/questions/1760371/…
  • 我的朋友我的问题是我不了解 sqlite 数据库并将数据存储在其中(不是存储字典)请指导我如何在 sqlite 中存储 nsdictionary

标签: ios objective-c json sqlite


【解决方案1】:

在以 NSDictionary 的形式解析您的数据后,您可以创建一个插入查询并触发查询,您的数据将被保存到您的数据库中

【讨论】:

  • @fred 创建一个方法,您只需将字典传递给该方法,该方法将使用 NSMutableString 创建一个插入查询以及字典中的键和值创建一个查询。
  • 我的朋友对不起,你能告诉我代码吗?我做第一部分,但第二部分是我的问题
  • 我已经发布了代码试试这个希望你会得到结果。
【解决方案2】:
-(void)InsertRecords:(NSMutableDictionary *)dict
{

sqlite3_stmt *stmt;
sqlite3 *cruddb;

NSMutableString *str = [NSMutableString stringWithFormat:@"Insert into tblName ("];

for (int i = 0; i<[[dict allKeys] count]; i++)
{
    [str appendFormat:@"%@,",[[dict allKeys] objectAtIndex:i]];
}
[str appendFormat:@")values ("];
for (int i = 0; i<[[dict allKeys] count]; i++)
{
    [str appendFormat:@"%@,",[dict valueForKey:[[dict allKeys] objectAtIndex:i]]];
}

[str appendFormat:@");"];
NSLog(@"qry : %@",str);
const char *sql = [str UTF8String]; ;

if((sqlite3_open([database UTF8String], &cruddb)==SQLITE_OK))
{
    if (sqlite3_prepare(database, sql, -1, &stmt, NULL) ==SQLITE_OK)
    {
        sqlite3_step(stmt);
        sqlite3_finalize(stmt);
    }
    else
    {
        NSLog(@"Problem with prepare statement: %s", sqlite3_errmsg(database));
    }
    sqlite3_close(database);
}
else
{
    NSLog(@"An error has occured: %s",sqlite3_errmsg(database));
}
}

试试这个。

【讨论】:

    【解决方案3】:

    继续@Divz Ans...

    您将创建 .sqlite 文件。没有比这更容易的了。

    有两种方法(我知道)来创建 sqlite 文件,

    1>您可以在firefox中下载SQLite Manager插件,您可以在其中以图形方式操作数据库中的数据。

    或者,

    2> 您可以将 Terminal 与单行命令 sqlite3 dbFileName.sqlite 一起使用。输入,

    您将在哪里获得 sqlite> 现在从进一步的 SQL(create/insert/update..) 查询开始。

    你可以在 MacHD>users>admin(not shared one)>yourFile.sqlite 或者 finder---go>home>yourFile.sqlite 找到你的 sqlite 文件

    【讨论】:

      【解决方案4】:
          static dispatch_once_t onceToken;
          dispatch_once(&onceToken, ^{
              db=[[SKDatabase alloc]initWithFile:@"student.sqlite"];
              NSURL *url=[NSURL URLWithString:@"..........Your Url............"];
              NSURLRequest *json_request=[[NSURLRequest alloc]initWithURL:url];
              NSData *data=[NSURLConnection sendSynchronousRequest:json_request returningResponse:nil error:nil];
              NSMutableDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
              NSMutableArray *student_ary=[dic objectForKey:@"students"];
      
              for (NSMutableArray *student_info in student_ary) {
                  NSMutableDictionary *insert=[[NSMutableDictionary alloc]initWithCapacity:2];
                  NSMutableDictionary *info=[student_info mutableCopy];
                  [insert setObject:[info objectForKey:@"name"] forKey:@"name"];
                  [insert setObject:[info objectForKey:@"city"] forKey:@"city"];
                  [db insertDictionary:insert forTable:@"student_info"];
      
              }
          })
      

      //.m 文件查看....

      -(void)viewDidAppear:(BOOL)animated
      {
          NSString *qry=@"select * from student_info";
          ary=[[db lookupAllForSQL:qry] mutableCopy];
          [tableView reloadData];
      }
      

      【讨论】:

        【解决方案5】:

        你可以这样做:

        - (UITableViewCell *)tableView:(UITableView *)tableView 
                 cellForRowAtIndexPath:(NSIndexPath *)indexPath
        {
            //  tableview cell setup
        
            NSArray* keys = [self.data allKeys];
        
            cell.textLabel.text = [self.data objectForKey:[keys objectAtIndex:indexPath.row]];
        
            return cell;
        }
        

        请参考this链接以在字典中按顺序排列数据

        NSDictionary with ordered keys

        【讨论】:

          猜你喜欢
          • 2013-05-12
          • 2012-01-07
          • 1970-01-01
          • 2012-06-14
          • 2020-09-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-12-20
          相关资源
          最近更新 更多