2011-07-27 59 views
0

只有一行效果但我希望效果4row一次我的代码正在为一行而不是其他值保存如何编写代码以保存在sqlite的多重值4row如何在我的sqlite数据库中一次插入多行sqlite中的iPhone

我尝试了很多,但我不知道如何插入不同的值在sqlite数据库中的不同行。

我对天气创建应用程序我得到的XML解析所有天气状况信息我解析表视图中的所有值我看到所有value.here在XML文件中的所有适当

我得到目前的状况元素和三个预测条件是表示今天显示的天气状况.and forecastcondition显示下一个3day天气状况.i为这个数据创建这个数据.3class与名称currentcondition和forecastcondition在forecastecondition元素中我有相同的名字next 3day元素名称意味着元素名称相同forecastcondition我存储所有在下一个3day值中逐个取值的数组中的预测条件值显示它在表格单元格中正确工作,我看到1cell上的当前条件值以及接下来的所有下一个3预测条件3cell我的代码是适当的工作,但现在我想存储第一个单元格值和下一个3day值单元格在SQLite数据库表中一次,但我怎么必须存储

但我保存当前条件在sqlite因为我creatcon对象currentcondition类然后我将值传递给sqlite,所以如何解析另一个单元格的值,但我的表是一个,我给所有的颜色名称在附加文件中,我想在此表中插入值coloum只有

我写这个代码存储sqlite请检查代码,这是我的控制器类,我在这里显示单元格的值,我只写了代码为sqlite保存数据,请帮助我的朋友

// 
    // TWeatherController.m 
    // Journey 
    // 
    // Created by pradeep.yadav on 5/3/11. 
    // Copyright 2011 __MyCompanyName__. All rights reserved. 
    // 

    #import "TWeatherController.h" 
    #import "TWeatherCell.h" 
    #import "ForecastInfoParser.h" 
    #import "global.h" 
    #define DATABASE_NAME @"test.sqlite" 
    #define DATABASE_TITLE @"test" 
    #import <sqlite3.h> 



    @implementation TWeatherController 
    @synthesize MyTableView; 
    @synthesize forecastcond; 

    #pragma mark - 
    #pragma mark View lifecycle 







    - (NSString *) getWritableDBPath { 

     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES); 
     NSString *documentsDir = [paths objectAtIndex:0]; 
     return [documentsDir stringByAppendingPathComponent:DATABASE_NAME]; 
    } 

    -(void)createEditableCopyOfDatabaseIfNeeded 
    { 
     // Testing for existence 
     BOOL success; 
     NSFileManager *fileManager = [NSFileManager defaultManager]; 
     NSError *error; 
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                  NSUserDomainMask, YES); 
     NSString *documentsDirectory = [paths objectAtIndex:0]; 
     NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:DATABASE_NAME]; 
     NSLog(@"%@",writableDBPath); 

     success = [fileManager fileExistsAtPath:writableDBPath]; 
     if (success) 
      return; 

     // The writable database does not exist, so copy the default to 
     // the appropriate location. 
     NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] 
            stringByAppendingPathComponent:DATABASE_NAME]; 
     success = [fileManager copyItemAtPath:defaultDBPath 
             toPath:writableDBPath 
             error:&error]; 
     if(!success) 
     { 
      NSAssert1(0,@"Failed to create writable database file with Message : '%@'.", 
         [error localizedDescription]); 
     } 
    } 


    -(BOOL) insertData 

    { 
    [self createEditableCopyOfDatabaseIfNeeded]; 
    //NSString *filePath = [self getWritableDBPath]; 
     BOOL value = NO; 

     @try { 

      sqlite3 *database; 
      if (sqlite3_open([[self getWritableDBPath] UTF8String], &database) != SQLITE_OK) 
      { 
       sqlite3_close(database); 
      } 
      else { 
       NSString *nsQuery = [[NSString alloc] initWithFormat:@"INSERT INTO weather (ReportDate,conditionname,humidity,maxtemp,mintemp,wind) VALUES('%@','%@','%@','%@','%@','%@')" ,_forecastInfo.CurrentDateTime,currentcond.Condition,currentcond.Tempf,currentcond.Tempf,currentcond.WindCondition,currentcond.Humidity]; 
       const char *query = [nsQuery UTF8String]; 
       [nsQuery release]; 

       sqlite3_stmt *statement; 
       int errorCode = sqlite3_prepare_v2(database, query, -1, &statement, NULL); 
       if(errorCode == SQLITE_OK) { 
        int result = sqlite3_step(statement); 
        if(result == SQLITE_DONE) { 
         value = YES; 
         sqlite3_finalize(statement); 
        } 
       } 
       sqlite3_close(database); 
      } 
     } 
     @catch (NSException *exception) { 
      NSLog(@"Error encountered while reading facts: %@", [exception reason]); 
     } 
     return value; 
    } 

    - (void)viewDidLoad { 
     [super viewDidLoad]; 
     _forecastInfo=nil; 
     currentcond=nil; 
     forecastcond=nil; 
     NSString *[email protected]"http://www.google.com/ig/api?weather=,,,50500000,30500000"; 
     NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:URL]]; 
     NSURLResponse *resp = nil; 
     NSError *err = nil; 
     NSData *response = [NSURLConnection sendSynchronousRequest: theRequest returningResponse: &resp error: &err]; 
     NSString * theString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]; 
     //[resp release]; 
     [err release]; 
     NSLog(@"response: %@", theString);  
     ForecastInfoParser *parser=[[ForecastInfoParser alloc]init]; 
     parser.delegate=self; 
     [parser parseData:response]; 


     //[self selected]; 
     [self insertData]; 


    } 


    -(void)forecastInfoParser:(ForecastInfoParser*)parser parsed:(ForecastInformation*)forecastInfo 
    { 
     _forecastInfo=[forecastInfo retain]; 
     [MyTableView reloadData]; 
    } 

    -(void)forecastInfo:(ForecastInfoParser*)parser parsed:(CurrentCondition*)currentcondition 
    { 
     currentcond=[currentcondition retain]; 
     [MyTableView reloadData]; 
    } 

    -(void)forecastInfoCondition:(ForecastInfoParser*)parser parsed:(NSMutableArray *)forecastcondition 
    { 
     forecastcond=[forecastcondition retain]; 
     [MyTableView reloadData]; 
    } 

    #pragma mark - 
    #pragma mark Table view data source 

    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
     // Return the number of sections. 
     return 1; 
    } 


    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
     if(_forecastInfo&&currentcond&&forecastcond) 
      return 4; 
     return 0; 

    } 


    // Customize the appearance of table view cells. 
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

     TWeatherCell *cell =(TWeatherCell *) [MyTableView dequeueReusableCellWithIdentifier:[NSString stringWithFormat:@"cell_%d", indexPath.row]]; 
     if (cell == nil) { 
      //cell = [[[TWeatherCell alloc] initWithStyle:UITableViewStyleGrouped reuseIdentifier:CellIdentifier] autorelease]; 
      cell = [[[TWeatherCell alloc] initWithFrame:CGRectZero reuseIdentifier:[NSString stringWithFormat:@"cell_%d", indexPath.row]] autorelease]; 
     } 
     //ForecastCondition *cond=[forecastcond objectAtIndex:0]; 
     cond1=[forecastcond objectAtIndex:1]; 
     cond2=[forecastcond objectAtIndex:2]; 
     cond3=[forecastcond objectAtIndex:3]; 
     if ([currentcond.Icon isEqualToString:@"http://\n"]) 
     { 
      cell.weatherimage.image = [UIImage imageNamed:@"listIcon-H.png"]; 
     } 
     else { 
      NSData *imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:currentcond.Icon]];  
      NSLog(@"this is image from server:%@",imageData); 
      cell.weatherimage.image = [UIImage imageWithData:imageData]; 
      [imageData release]; 
     } 
     NSDate *today = [NSDate date]; 
     NSDateFormatter *date_formatter=[[NSDateFormatter alloc]init]; 
     NSString *str=NSLocalizedString(@"date",nil); 
     [date_formatter setDateFormat:str]; 
     NSTimeInterval secondsPerDay = 24 * 60 * 60; 
     //NSDate *today = [NSDate date]; 
     NSDate *thursday = [NSDate dateWithTimeInterval:secondsPerDay sinceDate:today]; 
     NSDate *friday = [NSDate dateWithTimeInterval:2*secondsPerDay sinceDate:today]; 
     NSDate *sunday = [NSDate dateWithTimeInterval:3*secondsPerDay sinceDate:today]; 
     //tomorrow = [today addTimeInterval:secondsPerDay]; 
     switch (indexPath.row) { 
      case 0: 
       NSLog(@"%d",indexPath.row); 
       NSData *imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:currentcond.Icon]]; 
       NSLog(@"this is image from server:%@",imageData); 
       cell.weatherimage.image = [UIImage imageNamed:photo]; 
       [imageData release]; 
      file://localhost/Users/pradeepyadav/Desktop/JourneyMapper/Journey/Classes/TJourneyTabBar.hcell.weatherimage.image = [UIImage imageNamed:photo];  
       cell.reportdate.text = _forecastInfo.CurrentDateTime; 
       //cell.conditionname.text = currentcond.Condition; 
       [cell setConditionName:currentcond.Condition];  
       //[cell setConditionName:cond1.Condition]; 
       cell.twotemp.text = [NSString stringWithFormat:@"Temp:%@/%@",currentcond.Tempf,currentcond.Tempc]; 
       cell.twodirection.text = currentcond.WindCondition; 
       cell.humidity.text = currentcond.Humidity; 

       break; 
      case 1: 
       NSLog(@"%d",indexPath.row); 
       cell.weatherimage.image = [UIImage imageNamed:photo]; 
       cell.reportdate.text =[NSString stringWithFormat:@"%@",thursday]; 
       //cell.conditionname.text = cond1.Condition; 
       [cell setConditionName:cond1.Condition]; 
       cell.twotemp.text = [NSString stringWithFormat:@"Temp:%@/%@",cond1.Low,cond1.High]; 
       break; 
      case 2: 
       NSLog(@"%d",indexPath.row); 
       cell.weatherimage.image = [UIImage imageNamed:photo]; 
       cell.reportdate.text = [NSString stringWithFormat:@"%@",friday]; 
       //cell.conditionname.text = cond2.Condition; 
       [cell setConditionName:cond2.Condition]; 
       cell.twotemp.text = [NSString stringWithFormat:@"Temp:%@/%@",cond2.Low,cond2.High]; 
       break; 
      case 3: 
       NSLog(@"%d",indexPath.row); 
       cell.weatherimage.image = [UIImage imageNamed:photo]; 
       cell.reportdate.text = [NSString stringWithFormat:@"%@",sunday]; 
       //cell.conditionname.text = cond3.Condition; 
       [cell setConditionName:cond3.Condition]; 
       cell.twotemp.text = [NSString stringWithFormat:@"Temp:%@/%@",cond3.Low,cond3.High]; 
       break; 
      default: 
       NSLog(@"Out of Range ",indexPath.row); 
       break; 
     } 
     return cell; 
    } 






    #pragma mark - 
    #pragma mark Table view delegate 

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
     [tableView deselectRowAtIndexPath:indexPath animated:YES]; 
     // Navigation logic may go here. Create and push another view controller. 
     /* 
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil]; 
     // ... 
     // Pass the selected object to the new view controller. 
     [self.navigationController pushViewController:detailViewController animated:YES]; 
     [detailViewController release]; 
     */ 
    } 



    -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *) indexPath 
    { 
     return 100.0; 
    } 


    #pragma mark - 
    #pragma mark Memory management 

    - (void)didReceiveMemoryWarning { 
     // Releases the view if it doesn't have a superview. 
     [super didReceiveMemoryWarning]; 

     // Relinquish ownership any cached data, images, etc. that aren't in use. 
    } 

    - (void)viewDidUnload { 
     // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand. 
     // For example: self.myOutlet = nil; 
    } 


    - (void)dealloc { 
     [super dealloc]; 
     [_forecastInfo release]; 
     [currentcond release]; 
     [forecastConditions release]; 
    } 

    @end 

回答

0

我相信你问的是“如何在一个SQL命令中更新4行?”

最简单的方法是使用“;”分手的sql语句,形成一个字符串

你的主要SQL字符串似乎是NSString的nsQuery执行4次不同的查询,这里你可以设置它,虽然它有点乏味

NSString *qry1 = [NSString stringWithFormat:@"INSERT INTO weather (ReportDate,conditionname,humidity,maxtemp,mintemp,wind) VALUES('%@','%@','%@','%@','%@','%@')" ,_forecastInfo.CurrentDateTime,currentcond.Condition,currentcond.Tempf,currentcond.Tempf,currentcond.Wind2ondition,currentcond.Humidity]; 
NSString *qry2 = [NSString stringWithFormat:@"INSERT INTO newtable(DifferentColumn) VALUES('Dummy Data')"]; 
NSString *qry3 = [NSString stringWithFormat:@"INSERT INTO thirdtable(Temp) VALUES(3)"]; 
NSString *qry4 = [NSString stringWithFormat:@"INSERT INTO forthtable(Other) VALUES('indigo')"]; 

NSString *nsQuery = [[NSString alloc] initWithFormat:@"%@;%@;%@;%@",qry1,qry2,qry3,qry4]; 
+0

方式你可以提供一些示例代码 – Rani

+0

我必须插入相同的列和相同的表名也我不想插入不同的不同列 – Rani

+0

@AlanMacGredor我想插入值在同一个表中,并在那里列名 – Rani