如何遍历MySQL结果集? [英] How can I iterate through a MySQL result set?

查看:554
本文介绍了如何遍历MySQL结果集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我正在使用的代码:

Here is the code I'm using:

# 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)

在我看来,这是我看到值的方法:

In my View, here's what I do to see the values:

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

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

因此,假设我查询的是类似select * from Person的东西,并且返回的结果集如下:

So imagine I query something like select * from Person, and that returns a result set such as:

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

如何遍历每个值并输出呢?

How can I iterate through each value and output it?

这里的文档没有用,因为我尝试了应该存在的方法,但是解释器给我一个错误,指出这些方法不存在.我使用了错误的文档吗?

The documentation here is not useful because I have tried methods that supposedly exist, but the interpreter gives me an error saying that those methods don't exist. Am I using the wrong documentation?

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

谢谢!

推荐答案

如果您使用的是mysql2 gem,则应该获取mysql2结果对象,并且根据文档,您应该能够执行以下操作

If you are using mysql2 gem then you should be getting the mysql2 result object and according to the docs you should be able to do the following

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

此处

因此,您可以执行以下操作

So in you case you can do the following

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

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

Edit: you seem to be referring to the wrong doc check the Mysql2 gems doc.

这篇关于如何遍历MySQL结果集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆