如何遍历MySQL结果集?

这是我正在使用的代码:

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

在我的视图中,这是我看到的值:

 

Outputs: # Outputs: ["asdfasdf", 23, "qwefqwef"] ["sdfgdsf", 23, "asdfasdfasdf"]

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

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

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

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

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

谢谢!

如果您正在使用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://sofzh.miximages.com/mysql/398077070_b8795d0ef3_b.jpg end 

在这里查看文档

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

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

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

你可以尝试使用ActiveRecord::Base.connection.exec_query而不是ActiveRecord::Base.connection.execute ,它返回一个ActiveRecord::Result (在rails 3.1+中可用)

然后,您可以通过各种方式访问​​它,如.rows.each.to_hash

来自文档 :

 result = ActiveRecord::Base.connection.exec_query('SELECT id, title, body FROM posts') result # => # # 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 

使用:as => :hash

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

查找列标题的@ 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 

希望它有所帮助。