我从 MySQL 返回查询结果,我需要将它们附加到 csv 文件。我可以检索数据并成功显示,但无法将其写入 csv。到目前为止,这是我的 Ruby。
#! /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
最后一条语句给出了正确的结果:Impressions,"34,017"。当我删除它并在下面包含 CSV.open 语句时,我收到以下错误。第 87 行开始:csv <<
CSV.open("#{file_path}"'test_file.csv', "wb") do |csv|
series_1_results.each_hash do |s1|
csv << ["#{s1['label_imp']}","#{s1['impressions']}"]
end
end
test_csv.rb:87:in `[]': can't convert String into Integer (TypeError)
我正在运行 Ruby 1.9.2,感谢您的任何建议。