无法在iOS中将数据插入sqlite3

时间:2012-07-05 13:06:26

标签: ios sqlite

我正在尝试将文本数据插入iOS中的sqlite3数据库。

我编写了以下代码以将数据保存到sqlite3数据库中。

NSFileManager *fileMgr = [NSFileManager defaultManager];
        NSString *dbPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"MgDB.sqlite"];

        BOOL success = [fileMgr fileExistsAtPath:dbPath];

        if(!success)
        {
            NSLog(@"File Not Found");
        }

        if((!sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK))
        {
            NSLog(@"Error in MyInfo");
        }

        const char *sql = "Insert into MyDB (name,address,email) values('%@','%@','%@')";

        sqlite3_bind_text(sqlStmt, 0, [Name UTF8String], -1, SQLITE_TRANSIENT);
        sqlite3_bind_text(sqlStmt, 1, [Address UTF8String], -1, SQLITE_TRANSIENT);
        sqlite3_bind_text(sqlStmt, 2, [Email UTF8String], -1, SQLITE_TRANSIENT);

        if(sqlite3_prepare(database, sql, -1, &sqlStmt, NULL))
        {
            NSLog(@"Error in Loading database");
        }

        if (sqlite3_exec(database, sql, NULL, NULL, NULL) == SQLITE_OK) 
        {
            return sqlite3_last_insert_rowid(database);
        }


        if(sqlite3_step(sqlStmt) == SQLITE_ROW)
        {
            NSLog(@"ERROR");
        }
    }

    @catch (NSException *exception) 
    {
        NSLog(@"%@",exception);
    }

    @finally 
    {
        sqlite3_finalize(sqlStmt);
        sqlite3_close(database);
    }

根据我上面的代码,我返回最后一个插入ROWID以检查是否插入。

在View中保存文本数据后,ROWID已增加。

然而,当我使用FireFox sqlite3工具检查我的数据库时,我没有插入任何数据。

所以我停止运行并重新运行我的应用并再次添加数据。

最后一个插入ROWID与旧计数相同。即使只增加一个。

我想知道为什么它不会将任何数据保存到sqlite数据库中。

我的代码有问题吗?

请帮帮我。

提前致谢。

1 个答案:

答案 0 :(得分:1)

NSString *dbPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"MgDB.sqlite"];

您无法写入应用程序包中包含的文件。改为在Documents目录中创建(或复制)数据库。

请参阅QA1662