我正在尝试编写一个简单的createDB
函数。如果数据库文件不存在,我想创建它并继续。但是我在尝试创建文件时收到“没有这样的文件或目录”错误。
以下是代码片段:
-(void) createDB
{
NSString* docsDir;
NSArray* dirPaths;
// Get directory path
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
dbPath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:@"players.db"]];
NSFileManager* fileMgr = [NSFileManager defaultManager];
if([fileMgr fileExistsAtPath:dbPath] == NO)
{
//Create the file in main application folder
//dbPath = [[NSBundle mainBundle] pathForResource:@"players" ofType:@".db"];
if (![fileMgr createFileAtPath:dbPath contents:nil attributes:nil])
NSLog(@"Error was code: %d - message: %s", errno, strerror(errno));
// Above NSLog Prints : Error was code: 2 - message: No such file or directory
NSLog(@"DB PAth : %@",dbPath);
//Prints "DB Path : /Users/myname/Library/Application Support/iPhone Simulator/6.0/Applications/016E0BD6-E615-4031-A9E4-42E42D863ECB/Library/Documentation/"
if(sqlite3_open_v2([dbPath UTF8String], &playerDB, SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE, NULL) == SQLITE_OK)
{
char* errorMsg;
const char* sql_stmt = "CREATE TABLE IF NOT EXISTS PLAYERS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, GAME TEXT, GAME_DESC TEXT, DOB TEXT, IMAGE BLOB);";
if (sqlite3_exec(playerDB, sql_stmt, nil, nil, &errorMsg) != SQLITE_OK)
{
NSLog(@"%s Create Table '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(playerDB), sqlite3_errcode(playerDB));
}
}
else
NSLog(@"%s Open DB '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(playerDB), sqlite3_errcode(playerDB));
}
}
如果有人有任何意见,请告诉我。