Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
554 views
in Technique[技术] by (71.8m points)

ruby - How can I iterate through a MySQL result set?

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...