1

我正在尝试编写一个简单的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));
    }
}

如果有人有任何意见,请告诉我。

4

2 回答 2

0

替换NSDocumentationDirectory'

NSDocumentDirectory

我认为应该是

dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
于 2013-01-22T05:56:39.917 回答
0

我认为这条线有问题:

NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);

那应该是:

NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NS 文档目录

Documentation.

Available in iOS 2.0 and later.

Declared in NSPathUtilities.h.

NSDocument目录

Document directory.

Available in iOS 2.0 and later.

Declared in NSPathUtilities.h.

检查NSSearchPathDirectory以获取更多详细信息。

于 2013-01-22T05:57:16.500 回答