title: How to save database results to CSV in Ruby
body: <p>I am returning query results from MySQL and I need to append them to a csv file. I can retrieve the data and display it successfully but am having trouble getting it written to a csv. Here is my Ruby so far.</p>
  
  <pre><code>#! /usr/bin/ruby
  
  require 'mysql'
  require 'csv'
  
  # variables
  file_path = '/Users/pierce/tmp/'
  
  # need mysql queries here / use mysql2 calls
  test_db = Mysql.new("localhost", "root", "", "db")
  
  series_1_results = test_db.query("SELECT 'Impressions' AS label_imp,FORMAT(sum(impressions),',') AS impressions FROM table ")
  
  series_1_results.each_hash do |f|
    puts "#{f['label_imp']}"",\"""#{f['impressions']}""\""
  end
  </code></pre>
  
  <p>The last statement puts the correct result: Impressions,"34,017". When I remove it and include the CSV.open statement below I get the error that follows. Line 87 begins: csv &lt;&lt;</p>
  
  <pre><code>CSV.open("#{file_path}"'test_file.csv', "wb") do |csv|
      series_1_results.each_hash do |s1|
        csv &lt;&lt; ["#{s1['label_imp']}","#{s1['impressions']}"]
      end
  end
  
  test_csv.rb:87:in `[]': can't convert String into Integer (TypeError)
  </code></pre>
  
  <p>I am running Ruby 1.9.2 and appreciate any advice you have. </p>