如何迭代MySQL结果集?

Onl*_*ere 14 ruby mysql activerecord ruby-on-rails-3.2

这是我正在使用的代码:

# Run the query against the database defined in .yml file.
# This is a Mysql::result object - http://www.tmtm.org/en/mysql/ruby/
@results = ActiveRecord::Base.connection.execute(@sql_query)
Run Code Online (Sandbox Code Playgroud)

在我的视图中,这是我看到的值:

<pre><%= debug @results %></pre>
Outputs: #<Mysql2::Result:0x007f31849a1fc0>

<% @results.each do |val| %>
   <%= val %>
<% end %>
Outputs: ["asdfasdf", 23, "qwefqwef"] ["sdfgdsf", 23, "asdfasdfasdf"]
Run Code Online (Sandbox Code Playgroud)

所以想象一下我查询类似的东西select * from Person,然后返回一个结果集,例如:

ID      Name      Age
1       Sergio    22
2       Lazlow    28
3       Zeus      47
Run Code Online (Sandbox Code Playgroud)

如何迭代每个值并输出它?

这里的文档没有用,因为我已经尝试过可能存在的方法,但是解释器给出了一个错误,说明这些方法不存在.我使用了错误的文档吗?

http://www.tmtm.org/en/mysql/ruby/

谢谢!

Jos*_*hin 29

如果您正在使用mysql2 gem,那么您应该获取mysql2结果对象,并根据文档您应该能够执行以下操作

results.each do |row|
  # conveniently, row is a hash
  # the keys are the fields, as you'd expect
  # the values are pre-built ruby primitives mapped from their corresponding field types in MySQL
  # Here's an otter: http://farm1.static.flickr.com/130/398077070_b8795d0ef3_b.jpg
end
Run Code Online (Sandbox Code Playgroud)

这里查看文档

因此,在您的情况下,您可以执行以下操作

<% @results.each do |val| %>
   <%= "#{val['id']}, #{val['name']}, #{val['age']}" %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

编辑:你好像是指错误的doc检查Mysql2 gems doc.


haj*_*poj 11

您可以尝试使用ActiveRecord::Base.connection.exec_query而不是ActiveRecord::Base.connection.execute返回a ActiveRecord::Result(可在rails 3.1+中使用)

然后你就可以访问它以各种方式类似.rows,.each.to_hash

来自文档:

result = ActiveRecord::Base.connection.exec_query('SELECT id, title, body FROM posts')
result # => #<ActiveRecord::Result:0xdeadbeef>


# Get the column names of the result:
result.columns
# => ["id", "title", "body"]

# Get the record values of the result:
result.rows
# => [[1, "title_1", "body_1"],
      [2, "title_2", "body_2"],
      ...
     ]

# Get an array of hashes representing the result (column => value):
result.to_hash
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
      {"id" => 2, "title" => "title_2", "body" => "body_2"},
      ...
     ]

# ActiveRecord::Result also includes Enumerable.
result.each do |row|
  puts row['title'] + " " + row['body']
end
Run Code Online (Sandbox Code Playgroud)


cod*_*erz 5

使用:as => :hash

raw = ActiveRecord::Base.connection.execute(sql)
raw.each(:as => :hash) do |row|
  puts row.inspect # row is hash
end
Run Code Online (Sandbox Code Playgroud)