1

我的 Ruby 程序只是想调用一个存储过程(它将进行一些计算)并返回一个我想使用 Ruby 代码通过电子邮件发送的结果集。请注意,我没有使用 Rails,只是使用普通的 Ruby 和 mysql2 gems。

require 'active_record'

ActiveRecord::Base.establish_connection(
  :adapter => "mysql2",
  :host  => "localhost",
  :database => "<mydb>",
  :username => "<myusername>",
  :password => "<mypassword>"
)

class Rubyist < ActiveRecord::Base  
end

rubyist = Rubyist.new
puts rubyist.connection.execute("CALL ruby_routine")

返回以下错误

    Mysql2::Error: PROCEDURE students.ruby_routine can't return a result set in the given context: CALL ruby_routine (ActiveRecord::StatementInvalid)

现在我用谷歌搜索了这个并找到了链接,但它们是针对 Rails 应用程序的。我如何在纯 Ruby 中做到这一点?

4

2 回答 2

1

我认为问题来自 ActiveRecord 中使用的 mysql2 连接器。正如 mysql2 的人在他们的文档中所说:

您还可以检索多个结果集。为此,您需要连接标志 Mysql2::Client::MULTI_STATEMENTS。当调用返回多个结果集的存储过程时,通常使用多个结果集

因此,默认情况下未设置。对,所以理想情况下,如果你直接使用 mysql2 适配器(没有 ActiveRecord),你会像这样传递标志:

client = Mysql2::Client.new(:host => "localhost", :username => "root", :flags => Mysql2::Client::MULTI_STATEMENTS )

但是,由于您使用的是 ActiveRecord,因此您需要覆盖 mysql2 连接器。像这样的东西可以解决问题。

module ActiveRecord
  class Base
    # Establishes a connection to the database that's used by all Active Record objects.
    def self.mysql2_connection(config)
      config[:username] = 'root' if config[:username].nil?

      if Mysql2::Client.const_defined? :FOUND_ROWS
        config[:flags] = Mysql2::Client::FOUND_ROWS | Mysql2::Client::MULTI_STATEMENTS
      end

      client = Mysql2::Client.new(config.symbolize_keys)
      options = [config[:host], config[:username], config[:password], config[:database], config[:port], config[:socket], 0]
      ConnectionAdapters::Mysql2Adapter.new(client, logger, options, config)
    end
  end
end 
于 2013-02-19T17:07:01.107 回答
-2

你的问题是语法。尝试在“rubyist”类中​​移动“建立连接”方法。

于 2013-02-19T16:08:09.300 回答