我创建了一个应用程序,将数据存储到数据库中并读取它。我创建了一个.sql文件,并将其添加到资源文件夹中。我可以在模拟器上保存和检索数据,我的应用程序在模拟器上运行良好,但是当我在设备上安装相同的应用程序时,出现“没有这样的表”错误。

任何人都可以针对此问题提供解决方案。

这是我正在使用的代码块:

/////// Inside AppDelegate.m >>开始>>>

/////检查数据库是否存在>>>>

NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;

NSString *dbPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"TempDatabase.sql"];
BOOL success = [fileManager fileExistsAtPath:dbPath];

if(!success) {

    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"TempDatabase.sql"];
    success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];


    if (!success)

        NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);

} else {

    NSLog(@"Database file found at path %@", dbPath);

}


/////// Inside AppDelegate.m <<

////////在数据库中写入文件的逻辑>>>开始>>

           sqlite3 *pDb;
    char *databaseName;

    databaseName = @"TempDatabase.sql";

    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];
    //databasePath = [documentsDir stringByAppendingPathComponent:databaseName];

    databasePath =[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"TempDatabase.sql"];

    //[self copyDatabaseIfNeeded];


    if(sqlite3_open([databasePath UTF8String], &pDb) == SQLITE_OK)
    {

        const char *sqlStatement = "INSERT INTO tablename (name) VALUES(?)";

        sqlite3_stmt *compiledStatement;
        if(sqlite3_prepare_v2(pDb, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
        {


             sqlite3_bind_text( compiledStatement, 1, [strTxtFldValue UTF8String], -1, SQLITE_TRANSIENT);
        }
        if(sqlite3_step(compiledStatement) != SQLITE_DONE )
        {
             NSLog( @"~~~~~~~~~~~ 1 Error: %s", sqlite3_errmsg(pDb) );
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Name name is not added." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
            [alert release];

        } else {

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Confirmation" message:@"name is added successfully." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
            [alert release];

                }
        sqlite3_finalize(compiledStatement);
    }

    sqlite3_close(pDb);


////////在数据库<

最佳答案

您是否尝试过在运行时创建数据库。在运行时执行查询并创建表,尝试一下将对您有所帮助。

关于ios - 从iPhone设备读取和写入sqlite数据库中的数据时出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8851079/

10-12 14:36
查看更多