【问题标题】:Writing to SQLite in iOS/iPad development在 iOS/iPad 开发中写入 SQLite
【发布时间】:2012-08-07 22:39:23
【问题描述】:

我在 iPad 开发项目中写入 SQLite 数据库时遇到问题。这是我使用插入语句写入数据库的代码。我执行语句时sqlite没有发回错误但是数据仍然没有保存在数据库中。

我的插入语句的简化版本:

//Insert Into POHeader(CustID, CatalogName) Values('0', 'webdemo')


@try {
        NSFileManager *fileMgr = [NSFileManager defaultManager];
        NSString *dbPath = [[[NSBundle mainBundle] resourcePath]stringByAppendingPathComponent:@"Orders.db"];
        BOOL success = [fileMgr fileExistsAtPath:dbPath];
        if(!success)
        {
            NSLog(@"Cannot locate database file '%@'.", dbPath);
        }
        if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
        {
            NSLog(@"An error has occured: %@", sqlite3_errmsg(db));
        }

    sql = [self prepareSqlForPOHeader];
    sqlite3_stmt *sqlStatement;

    int sqlResult = (sqlite3_prepare_v2(db, sql, -1, &sqlStatement, NULL));

    if (sqlResult != SQLITE_OK)// (sqlite3_prepare_v2(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
    {
        NSLog(@"Problem with prepare statement:  %@", sqlite3_errmsg(db));
    }else{
        //success
    }

    sqlite3_finalize(sqlStatement);

}
@catch (NSException *exception) {
    NSLog(@"Problem with prepare statement: %@", sqlite3_errmsg(db));
}
@finally {
    sqlite3_close(db);
}

【问题讨论】:

  • 不完全是我的领域,但不应该有什么东西可以实际执行准备好的语句吗? (sqlite3_step?)
  • 虽然我对此进行了更多研究。应用程序中的数据库是通过将现有 SQLite 数据库拖放到资源文件夹中来创建的。这是否会使其成为只读然后 SQLite 由于某种原因没有返回此错误?

标签: ios ipad sqlite


【解决方案1】:

执行语句,这将起作用

【讨论】:

  • 谢谢你们。它似乎在一定程度上起作用,但仍然没有完全将插入一直提交到数据库。如果我连续两次执行相同的确切查询,它会给我一个“主键”错误,我认为这是一个好兆头,因为它表明查询正在执行。但是,如果我在第一次插入后运行 select 语句,则数据不在数据库中。我在这里错过了什么吗?它是否正在写入一些未提交到实际数据库中的临时数据库?
  • 老兄,你甚至没有执行插入。阅读 Sqlite
  • 我现在看到了。我没有意识到 sqlite3_step 是实际执行的原因。感谢您的帮助。
  • 那是一个查询 - 它也可能适用于插入/更新语句,但它并不意味着。谷歌在 Sqlite 上插入。
【解决方案2】:

您忘记添加此行:sqlite3_step(sqlStatement);

修改代码如下:

if ((sqlite3_prepare_v2(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
    NSLog(@"Problem with prepare statement:  %@", sqlite3_errmsg(db));
}
else
{
    sqlite3_step(sqlStatement);
    sqlite3_finalize(sqlStatement);
}

【讨论】:

  • 这正是缺少的。感谢您的帮助!
  • @user731659:很高兴:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-12
  • 1970-01-01
  • 2011-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多