Sqlite3_open: "cannot open database file"
I get "unable to open database file" when I execute 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));
}
sqlite3_open
returns an error if the database does not already exist. To create a database if it doesn't already exist, use sqlite3_open_v2
with flags SQLITE_OPEN_CREATE
and SQLITE_OPEN_READWRITE
( both are required ):
rc = sqlite3_open_v2(/* DB Path */, &db, SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE, NULL);
Link
To find /* DB PATH */
, you need to specify the filename in the document directory:
- (NSString *) applicationDocumentsDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
This convenience method can be used to concatenate the document 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);
#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 i am using;