本文介绍了sqlite3_open:“无法打开数据库文件”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

执行rc = sqlite3_open(test.db,& db)时,我得到无法打开数据库文件;

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));
}


推荐答案

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

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);

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

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);

这篇关于sqlite3_open:“无法打开数据库文件”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 14:54
查看更多