0

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.

5
  • You should check for, and log, errors reported by sqlite - they will probably tell you what is wrong. Commented Sep 11, 2011 at 18:02
  • @ufw: does this work? select col from table, that is, without the table-name prefixed to the column-name? Commented Sep 11, 2011 at 18:06
  • In both ways, SQLite log says it couldn't find an appropriate table. But, as I said before, I can get the data by standalone SQLite browser. Commented Sep 11, 2011 at 18:13
  • You have prepared the statement. Now how about executing it with sqlite3_step()? Commented Sep 11, 2011 at 18:23
  • Anyway I can't do that because something's wrong when it comes to the second "if" in the listing. Commented Sep 11, 2011 at 18:32

1 Answer 1

1

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"];

Sign up to request clarification or add additional context in comments.

1 Comment

If there is no DB in the specified path, a new, empty DB is created. Therefore, before opening a check must be made for existence, maybe the readonly DB from the resource dir must be copied to the doc dir.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.