Ruby mysql2 multiple statements in single query

一笑奈何 提交于 2019-12-05 19:04:46

Short answer to this problem is when MULTI_STATEMENTS are enabled mysql expects you to handle the result of your query.

A quick fix is to do something similar to this after each set of multiple update statements

  while db_write.next_result
    db_write.store_result rescue ''
  end

Why Dont you just ::

No need to run it multiple times ....

UPDATE pew SET x = 10 WHERE x IS NULL

As I understand it, this is a result Mysql internal protection - You are in the midst of querying DB, and streaming the results, if during that you'll also update the results, you can not guarantee any level of consistency.

If you KNOW you are safe to make changes as part of the flow, you could work around that by simply creating a second connection:

reading_client = Mysql2::Client.new(:host => 'localhost', :database => 'mehdb', :username => "root", :password => "", :flags => Mysql2::Client::MULTI_STATEMENTS)

updating_client = Mysql2::Client.new(:host => 'localhost', :database => 'mehdb', :username => "root", :password => "", :flags => Mysql2::Client::MULTI_STATEMENTS)


sql = "SELECT id, x FROM pew WHERE x IS NULL LIMIT 1000"

results = reading_client.query(sql)

while results.count > 0

  updates = ''

  results.each do |r|
    updates += "UPDATE pew SET x = 10 WHERE id = #{r['id']};"
  end

  updating_client.query(updates) unless updates.empty?

  results = reading_client.query(sql)
end

Before the next SQL statement write the following command.

ActiveRecord::Base.connection.raw_connection.abandon_results!

It will enable a new SQL command execution.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!