3

执行 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));
} 
4

2 回答 2

10

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

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

参考


要查找/* 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);
于 2012-06-28T18:41:17.633 回答
-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");

这是我使用的示例代码;

于 2014-09-14T06:47:54.430 回答