3

I get "unable to open database file" when executing rc = sqlite3_open("test.db", &db); ??

sqlite3 *db; // sqlite3 db struct
char *zErrMsg = 0;
int rc;

// Open the test.db file
rc = sqlite3_open("test.db", &db); // <-- creates DB if not found ??

if( rc ){
    // failed
    fprintf(stderr, "ERROR: Can't open database: %s\n", sqlite3_errmsg(db));
} 

2 Answers 2

10

sqlite3_open returns an error if the database does not already exist. To create the database if it doesn't already exist, use sqlite3_open_v2 with the SQLITE_OPEN_CREATE and SQLITE_OPEN_READWRITE flags (both are required):

rc = sqlite3_open_v2(/* DB Path */, &db, SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE, NULL);

Reference


To find /* DB PATH */, you need to base the filename off of the documents directory:

- (NSString *) applicationDocumentsDirectory 
{    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    return basePath;
}

You can use this convenience method to combine the documents path with the database name:

NSString *documents = [self applicationDocumentsDirectory];
NSString *dbPath = [documents stringByAppendingPathComponent:@"test.db"];

rc = sqlite3_open_v2([dbPath UTF8String], &db, SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE, NULL);
Sign up to request clarification or add additional context in comments.

13 Comments

Thank you I had tried that and got "ERROR: Can't open database: out of memory" ??
Where is test.db located (or should be created)?
My understanding is if the file is not present, it will create it?
Yes, but you can only write to the documents directory, so the path needs to be based there.
Things may have changed since 2012, I'm not sure, but at the moment the documentation states that sqlite3_open() does READWRITE and CREATE flags by default: sqlite.org/c3ref/open.html
|
-1
#define SQLITE_OK 0
sqlite3 *db;
char *zErrMsg=0;
if(sqlite3_open("demo.db", &db) == SQLITE_OK)
{
    if(sqlite3_exec(db, "select * from Users", callback, 0, &zErrMsg) == SQLITE_OK)
            msgbox1("success");
    sqlite3_close(db);
}
else
    msgbox1("failure");

here is the sample code which i use;

Comments

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.