2012-05-31 52 views
9

這裏是我使用的代碼:如何迭代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) 

在我看來,這是我做的,看的價值觀:

<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/

謝謝!

回答

23

如果您正在使用mysql2寶石,那麼你應該得到的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 

結帳的文檔here

所以你情況下,你可以做以下

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

編輯:你似乎是指的是錯誤的文檔檢查Mysql2寶石文檔。

+0

非常感謝!我不相信我在讀錯誤的文檔。 :) –

+5

可能過度工作休息一下。 – Josnidhin

+1

Nice otter .... – RTF

2

使用:as => :hash

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

使用'(:as =>:hash)'而不僅僅是'.each'有什麼好處? – Termato

+1

@Termato在我的筆記本電腦(Windows 7),Rails 3中,它不會輸出'row'作爲散列,因此我顯式地添加了'(:as =>:hash)'。完全同意只需使用'.each'如果它工作:) – coderz

+0

謝謝,這是非常有幫助的。 – Termato

6

你可以嘗試使用的ActiveRecord::Base.connection.exec_query代替ActiveRecord::Base.connection.execute這(在軌3.1+可用)

返回ActiveRecord::Result然後你就可以訪問它以各種方式像.rows.each,或.to_hash

docs

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 
1

查找列標題的@ results.fields。

示例:@Results = [[1 「塞爾吉奧」,22],[2, 「Lazlow」,28],[3, 「宙斯」,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 

希望它是很有幫助。