执行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));
}
答案 0 :(得分:10)
sqlite3_open
将返回错误。要创建数据库(如果该数据库尚不存在),请使用带有sqlite3_open_v2
和SQLITE_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);
答案 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");
这是我使用的示例代码;