0

我有一些代码每 10,000 次迭代执行一次。我正在使用模数,if i % 10000 == 0然后做一些事情。您pg_conn.exec function在代码中看到 ( ) 下面的“某些东西”,但无论如何我的问题是,pg_conn.exec 也需要为最后剩余的迭代完成,这实际上可能无法均匀地被 10,000 设计。我怎样才能做到这一点?我的程序执行了pg_conn.exec函数 5 次,因此变量i等于 50000。程序总共调用了 56,000 次迭代。如何处理剩余的 6,000 次迭代?

conn.query("select * from my_tbl") do |r|
    sql += "('#{r[:main_id]}', '#{r[:rep_dt]}', '#{r[:create_dt]}')"

    if i % 10000 == 0
    pg_conn.exec(sql + ';') # important statement that executes only every 10000
    end
end
4

2 回答 2

1

只需在块外再次调用代码即可。记得在 if 块中重置你的 sql 字符串:)

更新:添加了一个检查,以便pg_conn.exec只有在 sql 中发生更改时才会执行最后一次调用。

base_sql_statement = ... # base sql statement here
sql = base_sql_statement

conn.query("select * from my_tbl") do |r|
  sql += "('#{r[:main_id]}', '#{r[:rep_dt]}', '#{r[:create_dt]}')"

  if i % 10000 == 0
    pg_conn.exec(sql + ';') # important statement that executes only every 10000
    sql = base_sql_statement
  end
end

if sql != base_sql_statement
  pg_conn.exec(sql + ';')
end
于 2013-03-19T15:57:36.690 回答
0

从您的代码块中不清楚来自哪里i,但您需要知道最大值i是多少才能识别​​您是否在剩余组中。假设您可以掌握 max_i,请将您的电流替换ifif i % 10000 == 0 || i > ((max_i / 10000) * 10000)以利用整数算术。

于 2013-03-19T18:29:08.347 回答