0

我的目标是 iOS 5.1 并尝试将数据库从我的应用程序文件复制到我的 Documents 文件夹。我过去曾在应用程序上使用相同的代码完成此操作,所以我有点困惑为什么这次它不起作用。

这是我用来检查它是否存在并在不存在时复制它的方法。它来自这里

-(void) checkAndCreateDatabase{
// Check if the SQL database has already been saved to the users phone, if not then copy it over
BOOL success;

// Create a FileManager object, we will use this to check the status
// of the database and to copy it over if required
NSFileManager *fileManager = [NSFileManager defaultManager];

// Check if the database has already been created in the users filesystem
success = [fileManager fileExistsAtPath:self.databasePath];

// If the database already exists then return without doing anything
if(success) return;

NSLog(@"Installing db: %@", self.databasePath);
// If not then proceed to copy the database from the application to the users filesystem

// Get the path to the database in the application package
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];

// Copy the database from the package to the users filesystem
[fileManager copyItemAtPath:databasePathFromApp toPath:self.databasePath error:nil];

//[databasePathFromApp release];
//[fileManager release];

}

当我尝试查询数据库时,我这样做:

sqlite3 *database1; 

// Open the database from the users filessytem
if(sqlite3_open([self.databasePath UTF8String], &database1) == SQLITE_OK) {
    // Setup the SQL Statement and compile it for faster access

    NSString *sqlStatement = [NSString stringWithFormat: @"update login set is_logged=0"];
    sqlite3_stmt *compiledStatement;

    if(sqlite3_prepare_v2(database1, [sqlStatement UTF8String], -1, &compiledStatement, NULL) == SQLITE_OK) {

        if(SQLITE_DONE != sqlite3_step(compiledStatement)){
            NSAssert1(0, @"Error while updating logged. '%s'", sqlite3_errmsg(database1));
            NSLog(@"Error setting logged_in to 0: %s", sqlite3_errmsg(database1));
        }
        else{
            NSLog(@"Made Logged_in=0");
        }
    }
    else{
        NSLog(@"Prop problem1: %s", sqlite3_errmsg(database1));
        NSLog(@"Couldn't prep 1");
    }
    // Release the compiled statement from memory
    sqlite3_finalize(compiledStatement);
}
else{

    NSLog(@"Couldn't even open db1");
}
sqlite3_close(database1);

在这种情况下,该sqlite3_open()函数返回 false 并带有sqlite3_errmsgof no such table: login

我有一个每秒调用一次的函数,它创建一个使用此数据库对象的对象。会不会是数据库在那一秒内没有被复制,下一个调用中断了之前的复制?这听起来不太可能。

任何想法可能是什么问题?

解决方案 我咨询了这个问题:在这里,根据第 2 点,我的数据库似乎不在“复制捆绑资源”列表中。我添加了它,现在一切似乎都很好。

感谢你们让我朝着正确的方向思考。

4

1 回答 1

1

尝试验证复制过程的每个阶段是否返回一个有效对象。可能是(例如)您在搜索资源路径时没有包含扩展名。我倾向于使用 NSBundlepathForResource:ofType函数从包中获取内容。此外,对于空数据库,如果数据库不存在,sqlite 的 open 函数会创建一个数据库,然后打开它。尝试从copyItemAtPath

于 2012-03-14T16:00:28.693 回答