无法复制数据库

时间:2012-03-14 15:18:42

标签: iphone ios xcode ios5.1

我的目标是iOS 5.1并尝试将数据库从我的应用程序文件复制到我的Documents文件夹。我过去在应用程序上使用相同的代码完成了这一点,所以我有点混淆为什么它不能正常工作。

这是我用来检查它是否存在的方法,如果不存在则复制它。它来自here

-(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_errmsgno such table: login

我有一个每秒调用的函数,它创建一个使用该数据库对象的对象。可能是数据库还没有在那一秒被复制而下一次调用正在中断前一个副本?这听起来不太可能。

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

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

感谢让我思考正确的方向。

1 个答案:

答案 0 :(得分:1)

尝试验证复制过程的每个阶段是否返回有效对象。可能是(例如)您在搜索资源路径时未包含扩展名。我倾向于支持NSBundle pathForResource:ofType函数来从bundle中获取东西。另外,关于空DB,sqlite的open函数会创建一个数据库(如果它不存在),然后打开它。尝试从copyItemAtPath

获取错误
相关问题