1

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

我收到的最后一个错误是:database3[30351:c07] -[ViewController searchICAO:] 1st SQL error 'library routine called out of sequence' (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);
}
4

1 回答 1

0

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

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

于 2013-07-12T21:54:12.203 回答