如何从json存储在sqlite数据库中

时间:2013-04-29 08:48:09

标签: ios objective-c json sqlite

我创建了一个应用程序,我在JSON的表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”&amp;“date_string”值。 请指导我!!!

5 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

-(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));
}
}

试试这个。

答案 2 :(得分:0)

你可以这样做:

- (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

答案 3 :(得分:0)

继续@Divz Ans ...

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

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

1&GT;您可以在firefox中下载 SQLite Manager 加载项,您可以在其中以图形方式处理数据库中的数据。

或者,

2 - ;您可以使用终端使用单行命令 sqlite3 dbFileName.sqlite 。输入,

您将获得 sqlite&gt; ,现在开始进一步的SQL(创建/插入/更新..)查询。

你可以在MacHD上找到你的sqlite文件&gt;用户&gt; admin(不是共享的)&gt; yourFile.sqlite或者,finder --- go&gt; home&gt; yourFile.sqlite

答案 4 :(得分:0)

    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 file view ....

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