2012-05-31 6 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 결과 개체를 받고되어야하고 문서에 따라 당신에 here

그래서 다음

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 

체크 아웃에게 문서를 할 수 있어야 mysql2 보석을 사용하는 경우 당신이 것 같다 : 경우 당신은 다음

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

편집 할 수 잘못된 문서를 참조하여 Mysql2 gems doc을 확인하십시오.

+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

'.each'가 아닌'(: as => : hash)'를 사용하면 어떤 이점이 있습니까? – Termato

+1

@Termato 필자의 랩탑 (Windows 7), Rails 3에서는'row'를 해시로 출력하지 않으므로'(: as :> : hash)'를 명시 적으로 추가합니다. 완전히 작동하는 경우'.each'를 사용하는 것에 완전히 동의합니다. :) – coderz

+0

감사합니다. 매우 도움이됩니다. – Termato

6

당신은, 당신은 .rows, .each 같은 다양한 방법으로 액세스 할 수 ActiveRecord::Base.connection.exec_query 대신

을 (레일 3.1에서 사용 가능)를 ActiveRecord::Result 반환 ActiveRecord::Base.connection.execute의를 사용하여 시도 할 수 또는 .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 

는 그것이 희망 도움이됩니다.

관련 문제