使用Sqlite 3为IOS / Objective-C批量插入/插入多行

时间:2016-06-21 14:48:34

标签: ios objective-c iphone sqlite

免责声明:我使用的是sqlite3版本3.7.17。

我试图在名为block的空sqlite表中插入大约45000行。我不想使用多个插入语句,因为所有插入都需要大约12秒(即使我将所有内容分组到#34; BEGIN TRANSACTION" /" END TRANSACTION")

然后我在sqlite中查找了批量插入方法,我找到了this主题,这显然帮助了很多人。我尝试复制所提供的伪代码的两个版本(使用UNION ALL和INSERT VALUES)。当我打印我的查询时,它们看起来都是正确的。但是,数据未写入数据库。

这是我的代码:

const char* mega_query_blocks =
"insert into block "
"select ? as p, ? as q, ? as x, ? as y, ? as z, ? as w "
"union all select ?, ?, ?, ?, ?, ? "
"union all select ?, ?, ?, ?, ?, ? "
"union all select ?, ?, ?, ?, ?, ? "
"union all select ?, ?, ?, ?, ?, ? "
"union all select ?, ?, ?, ?, ?, ? "
"union all select ?, ?, ?, ?, ?, ? "
"union all select ?, ?, ?, ?, ?, ?";

- (void) _db_mega_insert_block: (Block *) block atPosition: (int) position
{
  int mod_position = position % 8;

  if (mod_position == 1 && position > 1) {
      sqlite3_step(data->mega_blocks_stmt);
      sqlite3_clear_bindings(data->mega_blocks_stmt);
      sqlite3_reset(data->mega_blocks_stmt);
  }
  sqlite3_bind_int(data->mega_blocks_stmt, 6 * (mod_position - 1) + 1, block.p);
  sqlite3_bind_int(data->mega_blocks_stmt, 6 * (mod_position - 1) + 2, block.q);
  sqlite3_bind_int(data->mega_blocks_stmt, 6 * (mod_position - 1) + 3, block.x);
  sqlite3_bind_int(data->mega_blocks_stmt, 6 * (mod_position - 1) + 4, block.y);
  sqlite3_bind_int(data->mega_blocks_stmt, 6 * (mod_position - 1) + 5, block.z);
  sqlite3_bind_int(data->mega_blocks_stmt, 6 * (mod_position - 1) + 6, block.w);
}

sqlite3_open([filePath UTF8String], &data->db);    

sqlite3_prepare_v2(data->db, mega_query_blocks, -1, &data->mega_blocks_stmt, NULL);

sqlite3_exec(data->db, "BEGIN TRANSACTION;", NULL, NULL, NULL);
// iterate over blocks here
  [self _db_mega_insert_block:block atPosition:position];

sqlite3_exec(data->db, "END TRANSACTION;", NULL, NULL, NULL);

sqlite3_finalize(data->mega_blocks_stmt);
sqlite3_close(data->db);

您是否对未插入数据的原因有任何想法,即使所有查询都正确打印,哪些有效值代替问号?

谢谢!

PS:显然这里没有线性显示代码,但实际上这就是它正在发生的事情。

0 个答案:

没有答案