从iphone设备读取和写入sqlite数据库中的数据时出错

时间:2012-01-13 13:08:23

标签: ios ios4 ios5

我创建了一个应用程序,我将数据存储到数据库中并读取它。我创建了一个.sql文件并将其添加到资源文件夹中。我可以通过模拟器保存和检索数据,我的应用程序在模拟器上工作正常,但当我在设备上安装相同的应用程序时,我收到错误,因为“没有这样的表格”

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

以下是我使用的代码块:

///////在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);

}

///////在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);

///////在数据库中写入文件的逻辑<<

1 个答案:

答案 0 :(得分:1)

您是否尝试过在运行时创建数据库。在运行时执行查询并创建表,试试这个肯定会帮助你。