【问题标题】:Strange SQLite behavior奇怪的 SQLite 行为
【发布时间】:2009-06-27 16:54:24
【问题描述】:

我正在向表中插入数据,sqlite3_step 返回 SQLITE_DONE。但有时表中没有新数据!即使我在添加数据后立即进行检查。

这是我的代码:

sqlite3_stmt *addTranslationStmt2 = NULL;

if(sqlite3_prepare_v2( database , "INSERT INTO translations(lang1_wordid, lang2_wordid) VALUES(?, ?)" , -1, & addTranslationStmt2, NULL) != SQLITE_OK)
{
  NSLog(@"statement prepare error");
  addTranslationStmt2 = NULL;
  return -1;
}

sqlite3_bind_int(addTranslationStmt2, 1, word_id);
sqlite3_bind_int(addTranslationStmt2, 2, translation_id);

if(sqlite3_step(addTranslationStmt2) != SQLITE_DONE)
{
  NSLog(@"addTranslationStmt2 error: '%s'", sqlite3_errmsg(database));
  sqlite3_reset(addTranslationStmt2);
  return -1;
}

sqlite3_reset(addTranslationStmt2);

if (![self wordHasTranslation: word_id translation_id: translation_id])
  NSLog(@"And after all translation was not added even though sqlite3_step returns SQLITE_DONE!");

所以我想知道为什么最后提到的日志函数被调用了。这意味着添加数据后表中没有数据。有时会添加,有时不会。

问题可能出在哪里? 提前谢谢你。

更新: 我发现只有在创建新数据库时才会发生这种情况。应用程序重新启动后,它以正确的方式工作。但是如果创建了一个新的数据库,奇怪的行为又回来了。

【问题讨论】:

  • 有没有可能是 wordHasTranslation 出了问题?
  • 不,它只是一个告诉我是否添加了数据的函数。我什至手动检查了数据库——没有新数据的迹象。即使当我在代码的其他部分插入其他数据时,一切正常。

标签: iphone sqlite


【解决方案1】:

默认情况下,Sqlite 确实在自动提交模式下运行,但我们无法知道之前的某些交互或设置是否会重置;如果在INSERT 之后添加显式COMMIT,有帮助吗?

编辑:可能不会,请从 cmets 提供更多信息,但以防万一您确实需要在其他情况下提交,最简单的方法是:

char* errmsg;
int result = sqlite3_exec(database, "COMMIT", NULL, NULL, &errmsg);

使用通常的结果代码 &c(在使用它指向的错误消息后,您需要sqlite3_free(errmsg),如果有的话)。

【讨论】:

  • 您能告诉我如何添加显式 COMMIT 吗?我不太熟悉。
  • 提交后我收到以下错误:“无法提交 - 没有事务处于活动状态”有什么想法吗? ..
  • 我试图用 BEGIN/COMMIT 语句包装代码,但错误仍然存​​在..
  • 感谢您的帮助,我发现了错误所在 - 我最终确定了一个错误的陈述。
  • 嗯,感谢您更新我们的信息! “无法提交”意味着您确实将自动提交设置为 true,因为它默认为...
猜你喜欢
  • 2012-05-16
  • 2015-07-11
  • 1970-01-01
  • 1970-01-01
  • 2020-01-30
  • 2013-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多