sqlite3_open:“无法打开数据库文件”

时间:2012-06-28 18:36:16

标签: c cocoa-touch sqlite

执行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 个答案:

答案 0 :(得分:10)

如果数据库尚不存在,

sqlite3_open将返回错误。要创建数据库(如果该数据库尚不存在),请使用带有sqlite3_open_v2SQLITE_OPEN_CREATE标记的SQLITE_OPEN_READWRITE两者都是):

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

Reference


要查找/* DB PATH */,您需要将文件名基于文档目录:

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

您可以使用此便捷方法将文档路径与数据库名称组合在一起:

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

rc = sqlite3_open_v2([dbPath UTF8String], &db, SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE, NULL);

答案 1 :(得分:-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");

这是我使用的示例代码;