17

这是我正在使用的代码:

# 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

4 回答 4

33

如果您使用的是 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

在此处查看文档

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

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

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

于 2012-05-31T15:47:56.447 回答
15

您可以尝试使用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
于 2016-05-24T02:06:44.520 回答
5

使用:as => :hash

raw = ActiveRecord::Base.connection.execute(sql)
raw.each(:as => :hash) do |row|
  puts row.inspect # row is hash
end
于 2015-01-07T08:32:31.337 回答
2

查找列标题的@results.fields。

示例:@results = [[1, "Sergio", 22],[2, "Lazlow", 28],[3, "Zeus", 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

希望它是有帮助的。

于 2016-08-30T12:04:12.427 回答