如何遍历 MySQL 结果集?
这是我正在使用的代码:
# 对 .yml 文件中定义的数据库运行查询.# 这是一个 Mysql::result 对象 - http://www.tmtm.org/en/mysql/ruby/@results = ActiveRecord::Base.connection.execute(@sql_query)
在我看来,以下是我为查看值所做的操作:
<%= debug @results %>
输出:#<Mysql2::Result:0x007f31849a1fc0><% @results.each 做 |val|%><%=val%><%结束%>输出: ["asdfasdf", 23, "qwefqwef"] ["sdfgdsf", 23, "asdfasdfasdf"]
假设我查询了类似 select * from Person
的内容,然后返回一个结果集,例如:
ID 姓名 年龄1 塞尔吉奥 222 拉兹洛 283 宙斯 47
如何遍历每个值并输出它?
这里的文档没有用,因为我尝试了应该存在的方法,但是解释器给了我一个错误,说这些方法不存在.我是否使用了错误的文档?
http://www.tmtm.org/en/mysql/ruby/
谢谢!
解决方案如果您使用的是 mysql2 gem,那么您应该获得 mysql2 结果对象,根据文档,您应该能够执行以下操作
results.each do |row|# 方便的是,row 是一个散列# 键是字段,正如你所期望的# 这些值是从 MySQL 中对应的字段类型映射的预构建的 ruby 原语# 这是一只水獭:http://farm1.static.flickr.com/130/398077070_b8795d0ef3_b.jpg结尾
查看文档这里
因此,您可以执行以下操作
<% @results.each do |val|%><%= "#{val['id']}, #{val['name']}, #{val['age']}" %><%结束%>
编辑:您似乎指的是错误的文档,请检查 Mysql2 gems 文档.
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"]
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/
Thanks!
解决方案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
Checkout the documentation here
So in you case you can do the following
<% @results.each do |val| %>
<%= "#{val['id']}, #{val['name']}, #{val['age']}" %>
<% end %>
Edit: you seem to be referring to the wrong doc check the Mysql2 gems doc.
相关文章