无法查询我的sqlite数据库

时间:2013-07-12 15:39:32

标签: ios sql sqlite

下面是我的代码,我正在尝试从用户输入的文本字段中的机场城市名称查询sqlite数据库中检索数据,并检索要在标签中显示的ICAO标识符。似乎db正在加载,但是当我选择IBAction按钮时它不会查询。我认为我的查询语句或我的数据库可能有问题,虽然我不能在这里列出。非常感谢任何帮助。

我收到的最后一个错误是:database3 [30351:c07] - [ViewController searchICAO:]第一个SQL错误'库程序不按顺序调用'(21)

-(NSString*)filePath {
    NSArray*paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    return [[paths objectAtIndex:0]stringByAppendingPathComponent:@"mydatabase.sqlite"];
}

//open database
- (void)viewDidLoad{

    [self openDB];
}


-(void)openDB {

    if(sqlite3_open([[self filePath]UTF8String], &airportDB) !=SQLITE_OK) {
        sqlite3_close(airportDB);
        NSAssert(0, @"Databese failed to open");
        status.text = @"Database Failed to Open";
    }
    else if (sqlite3_open([[self filePath]UTF8String], &airportDB) ==SQLITE_OK) {//this line not really needed but was trying everything
        NSLog(@"database opened");          //test
        status.text = @"Database Opened";  //test
    }
}

- (IBAction)searchICAO:(id)sender
{
    //[self.delegate detailViewControllerDidFinish:self]; //for later use


    //Get airport name from the text field user enters
    NSString*sql = [NSString stringWithFormat:@"SELECT * FROM airports WHERE city=\"%@\"", [searchDB text]];

    const char *query_stmt = [sql UTF8String];

    sqlite3_stmt *statement;

    NSLog(@"%s 1st SQL error '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(airportDB), sqlite3_errcode(airportDB));  //Error Test

这就是我似乎遇到问题的地方......

    if (sqlite3_prepare_v2(airportDB, query_stmt, -1, &statement, NULL)==SQLITE_OK) {// Problem is from here, can't get past this point

        NSLog(@"%s 2nd SQL error '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(airportDB), sqlite3_errcode(airportDB));  //Error Test

        if (sqlite3_step(statement)==SQLITE_ROW) {

            status.text = @"";  //Clear the status line

            NSString *returnICAO = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 1)];
            status.text = returnICAO;  //Insert Airport ICAO letters from the database table 

        }

        sqlite3_finalize(statement);

        [super viewDidLoad];
    }
    sqlite3_close(airportDB);
}

1 个答案:

答案 0 :(得分:0)

我没有看到究竟出了什么问题,但我会提出这一点,除非您有使用第三方代码无法满足的特定目标,否则您应该考虑使用FMDB https://github.com/ccgus/fmdb - 假设您需要直接去SQLite。我已经使用了很多,并且取得了很好的成功。

关闭数据库并从searchICAO调用[super viewDidLoad]有点奇怪:这是故意的吗?看来这可能是你问题的根源?在第二个查询中,数据库将被关闭?