Mark
Mark

Reputation: 2038

sqlite3_prepare_v2 is getting SQLITE_ERROR

I have been at this for hours and MUST get this working! It is holding up an iPhone app release... My first time using SQLite. I have followed all the advice and yet my sqlite3_prepare_v2 call gets a SQLITE_ERROR (1) every time!

Here is my code from my controller:

        NSString *query = @"SELECT * FROM QandA ORDER BY random() LIMIT 1";
//  const char *sqlStatement = "SELECT * FROM QandA ORDER BY random() LIMIT 1";
    sqlite3_stmt *compiledStatement;

    // sqlite3_stmt *statement;
    int prepareStatus = sqlite3_prepare_v2(database, [query UTF8String],
                                           -1, &compiledStatement, NULL);
    if (prepareStatus == SQLITE_OK) {...

You'll note that I've tried using a "char *" also to no avail (among other attempts). My database opens fine with:

    databaseName = @"Facts.sqlite";
// Get the path to the documents directory and append the databaseName
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
NSLog(@"databasePath = %@", databasePath);

int dbOpenStatus = sqlite3_open_v2([databasePath UTF8String], &database, SQLITE_OPEN_READWRITE, NULL);

From my controller interface:

    NSString *databaseName;
NSString *databasePath;

I've checked in the debugger and everything looks good, but the prepare statement fails. I don't know how to log the statement it is trying to compile... I assume/hope it is just what my SELECT says.

Can anyone help? I'm desperate. Mark

Upvotes: 2

Views: 10638

Answers (3)

Chainfire
Chainfire

Reputation: 11

Please note that the above is slightly inaccurate, the ofType should be used not extension, and the ofType obviously needs to match your file extension.

If your DB is named "mysqldatabase.sql" change your path URL to:

databasePath = [[NSBundle mainBundle]pathForResource:@"mysqldatabase" ofType:@"sql"];

Upvotes: 1

Mark
Mark

Reputation: 2038

Found the answer here. I had to use this instead for the path to the DB file:

[[NSBundle mainBundle]pathForResource:@"Facts"extension:@"sqlite"];

This gave a slightly different path (one extra directory) - once I used that it worked! Hope this helps someone else... I spent many hours on this.

Upvotes: 6

Ernő Simonyi
Ernő Simonyi

Reputation: 365

The code seems to be fine, might be a silly question but have you created the QandA table inside of the database?

Upvotes: 0

Related Questions