如何在iPhone中的SQLite中一次插入多行?
在我的SQLite数据库中,只有一行效果,但我希望一次有4行效果。我的代码只适用于一行,不适用于其他值保存。如何编写在SQLite中保存多行的代码 我为天气创建应用程序。我通过XML解析获得所有天气状况信息,我解析表视图中的所有值,我看到所有值。这是完全正确的 在XML文件中,我得到了current condition元素和三个forecast condition,它表示当前条件,它显示今天的天气条件,forecast condition显示未来三天的天气条件。我创建了一个名为currentcondition和forecastcondition的类来获取这个数据 在forecastcondition元素中,我拥有与下一个3天相同的名称元素名称表示元素名称相同forecastcondition我将所有预测条件值存储在数组中,以便逐个获取下一个3天值,并在表格单元格中显示其正常工作。我在1单元格中看到当前条件值,在下一个3单元格中看到所有下一个3 ForecastCondition显示我的代码正常工作,但现在我想在sqlite数据库表中一次存储第一个单元格值和下一个3天值单元格,但我如何存储 但我将currentcondition保存在SQLite中,因为我创建了currentcondition类的对象,然后将值传递给SQLite。那么,如何同时解析另一个单元格值呢?我的表是一个,我在附件中给出了所有列名;我只想在此表列中插入值 我为store SQLite编写此代码,请检查代码。这是我的控制器类,在这里我在单元格上显示值,只有我为SQLite编写代码来保存数据如何在iPhone中的SQLite中一次插入多行?,iphone,objective-c,Iphone,Objective C,在我的SQLite数据库中,只有一行效果,但我希望一次有4行效果。我的代码只适用于一行,不适用于其他值保存。如何编写在SQLite中保存多行的代码 我为天气创建应用程序。我通过XML解析获得所有天气状况信息,我解析表视图中的所有值,我看到所有值。这是完全正确的 在XML文件中,我得到了current condition元素和三个forecast condition,它表示当前条件,它显示今天的天气条件,forecast condition显示未来三天的天气条件。我创建了一个名为currentco
//
// 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 *URL=@"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&¤tcond&&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
//
//TWeatherController.m
//旅程
//
//由pradeep.yadav于2011年5月3日创建。
//版权所有2011年uu MyCompanyName uuu。版权所有。
//
#导入“TWeatherController.h”
#导入“TWeatherCell.h”
#导入“ForecastingFoParser.h”
#导入“global.h”
#定义数据库名称@“test.sqlite”
#定义数据库标题@“测试”
#进口
@计算机控制器的实现
@综合MyTableView;
@综合预报秒;
#布拉格标记-
#pragma标记视图生命周期
-(NSString*)getWritableDBPath{
NSArray*Path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,是);
NSString*documentsDir=[paths objectAtIndex:0];
返回[documentsDir stringByAppendingPathComponent:DATABASE_NAME];
}
-(void)CreateEditableCopyOfDatabaseIf需要
{
//生存检验
成功;
NSFileManager*fileManager=[NSFileManager defaultManager];
n错误*错误;
NSArray*Path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,是);
NSString*documentsDirectory=[paths objectAtIndex:0];
NSString*writableDBPath=[DocumentsDirectoryStringByAppendingPathComponent:DATABASE_NAME];
NSLog(@“%@”,writeabledbpath);
成功=[fileManager fileExistsAtPath:writableDBPath];
如果(成功)
回来
//可写数据库不存在,因此将默认数据库复制到
//合适的位置。
NSString*defaultDBPath=[[[NSBundle mainBundle]资源路径]
stringByAppendingPathComponent:数据库_名称];
success=[fileManager copyItemAtPath:defaultDBPath
toPath:writeabledbpath
错误:&错误];
如果(!成功)
{
NSAssert1(0,@)无法创建可写数据库文件,消息为:'%@',
[错误本地化描述];
}
}
-(BOOL)插入数据
{
[根据需要自行创建可编辑的数据库副本];
//NSString*filePath=[self-getWritableDBPath];
布尔值=否;
@试试{
sqlite3*数据库;
if(sqlite3_打开([[self getwriteabledbpath]UTF8String],&database)!=SQLITE_确定)
{
sqlite3_关闭(数据库);
}
否则{
NSString*nsQuery=[[NSString alloc]initWithFormat:@“插入天气(报告日期、条件名称、湿度、最大温度、最小温度、风)值('%@'、'%@'、'%@'、'%@'、'%@'、'%@'、'%@'),_forecasting.CurrentDateTime、currentcond.Tempf、currentcond.Tempf、currentcond.WindCondition、currentcond.湿度];
常量字符*查询=[nsQuery UTF8String];
[nsQuery发布];
sqlite3_stmt*语句;
int errorCode=sqlite3\u prepare\u v2(数据库、查询、-1和语句,NULL);
如果(errorCode==SQLITE_OK){
int result=sqlite3\u步骤(语句);
如果(result==SQLITE_DONE){
值=是;
sqlite3_最终确定(声明);
}
}
sqlite3_关闭(数据库);
}
}
@捕获(NSException*异常){
NSLog(@“读取事实时遇到错误:%@,[异常原因]);
}
返回值;
}
-(无效)viewDidLoad{
[超级视图下载];
_forecastInfo=零;
currentcond=零;
预报秒=零;
NSString*URL=@”http://www.google.com/ig/api?weather=,,,50500000,30500000";
NSURLRequest*theRequest=[nsurlRequestWithURL:[nsurlUrlWithString:URL]];
NSURLResponse*resp=nil;
n错误*err=nil;
NSData*响应=[NSURLConnection sendSynchronousRequest:theRequest returningResponse:&resp error:&err];
NSString*字符串=[[NSString alloc]initWithData:响应编码:NSUTF8STRINGENCONDING];
//[重新发布];
[错误释放];
NSLog(@“响应:%@”,字符串);
ForecastingFoParser*解析器=[[Forecast]
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];