将值插入数据库的问题

时间:2011-04-08 08:37:01

标签: iphone sqlite

我熟悉sqlite并尝试将值插入数据库但却给出异常。 tf1和tf2是文本字段的对象。这是我的代码:

@synthesize tf1, tf2, add, disp;
-(id)initApp

{
if(![super init])
        return nil;

    //DB stored in application bundle
    NSString *DBName = @"kbase.sqlite";
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingString:DBName];

    db = [FMDatabase databaseWithPath:path];
    [db setLogsErrors:TRUE];
    [db setTraceExecution:TRUE];

    if(![db open])
    {
        NSLog(@"Could not open Database");
        return 0;
    }

    else
    {
        NSLog(@"Database opened successfully");
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self initApp];
    [add addTarget:self action:@selector(insertButtonClicked:)   forControlEvents:UIControlEventTouchUpInside]; 
    [disp addTarget:self action:@selector(displaytButtonClicked:)   forControlEvents:UIControlEventTouchUpInside]; 
}


-(IBAction)insertButtonClicked :(id)sender
{ 
    NSLog(@"insert");
    NSLog(@"db.....%@",db);
    [db executeUpdate:@"insert into info values (?,?)", tf1.text, tf2.text];

    [self resignFirstResponder];

}

-(IBAction)displayButtonClicked:(id)sender

{
    NSString *str1 = tf2.text;
    NSString *returnResult = [[NSString alloc]init];
    FMResultSet *rs = [db executeQuery:@"select name from info where rollno = 1"];

    while ([rs next])
    {
        returnResult = [rs stringForColumn:@"rollno"];
        [tf1 setText:returnResult];
        [tf2 setText:returnResult];
    }       
}

数据库打开成功并且在打印插入后控制终止 例外:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSURL executeQuery:]: unrecognized selector sent to instance 0x3d30ef0'

我无法配置问题。请帮助。

2 个答案:

答案 0 :(得分:0)

在这种情况下似乎不存在db。如果db是类变量,请确保它不会在其他位置释放。只需在执行上方加NSLog(@"%@", db);即可对其进行测试。

答案 1 :(得分:0)

我认为制作你的方法

[db executeUpdate:@“插入信息值(?,?)”withValue1:tf1.text withValue2:tf2.text];

而不是

[db executeUpdate:@“插入信息值(?,?)”,tf1.text,tf2.text];