如何迭代MySQL结果集?

时间:2012-05-31 15:39:02

标签: mysql ruby 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)

在我的视图中,以下是我查看值的方法:

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

<% @results.each do |val| %>
   <%= val %>
<% end %>
Outputs: ["asdfasdf", 23, "qwefqwef"] ["sdfgdsf", 23, "asdfasdfasdf"]

因此,想象一下我查询类似select * from Person的内容,并返回结果集,例如:

ID      Name      Age
1       Sergio    22
2       Lazlow    28
3       Zeus      47

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

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

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

谢谢!

4 个答案:

答案 0 :(得分:27)

如果您正在使用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

查看文档here

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

<% @results.each do |val| %>
   <%= "#{val['id']}, #{val['name']}, #{val['age']}" %>
<% end %>

编辑:您似乎是指错误的文档检查Mysql2 gems doc。

答案 1 :(得分:8)

您可以尝试使用ActiveRecord::Base.connection.exec_query代替ActiveRecord::Base.connection.execute,它会返回ActiveRecord::Result(在rails 3.1 +中可用)

然后,您可以通过.rows.each.to_hash

等多种方式访问​​它

来自docs

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

答案 2 :(得分:2)

使用:as => :hash

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

答案 3 :(得分:2)

查找列标题的@ results.fields。

示例:@results = [[1,&#34; Sergio&#34;,22],[2,&#34; Lazlow&#34;,28],[3,&#34; Zeus&#34; ,47]]

@results.fields do |f|
  puts "#{f}\t"  # Column names
end

puts "\n"

@results.each do |rows| # Iterate through each row
  rows.each do |col| # Iterate through each column of the row
    puts "#{col}\t"
  end
  puts "\n"
end

希望它有用。