简体   繁体   中英

iOS, SQLite: can't read from the DB

I have an SQLite database, I can open it with SQLite browser, execute queries to it etc. But I can't get any data from it in my Xcode project.

NSString *databaseName = @"dbFile.db";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
sqlite3 *database;

if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
    NSLog(@"db is ok"); // works just fine
    const char *sqlStatement = "SELECT table.column FROM table";
    sqlite3_stmt *compiledStatement;

    if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
        NSLog(@"OK"); // nothing happens
    }
    sqlite3_close(database);
}

The very same query executed from SQLite browser for Mac works just fine.

sqlite3_open doesn't report all errors until you start accessing the data. For example just about any filename and path will pass without errors.

Are you sure the database is in the Documents folder? It's not there by default. Perhaps it's in the main bundle?

Try NSString *databaseName = [[NSBundle mainBundle] pathForResource:@"dbFile" ofType:@"db"];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM