简体   繁体   English

如何在Ruby中将数据库结果保存为CSV

[英]How to save database results to CSV in Ruby

I am returning query results from MySQL and I need to append them to a csv file. 我从MySQL返回查询结果,我需要将它们附加到一个csv文件中。 I can retrieve the data and display it successfully but am having trouble getting it written to a csv. 我可以检索数据并成功显示它,但是很难将其写入csv。 Here is my Ruby so far. 到目前为止,这是我的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

The last statement puts the correct result: Impressions,"34,017". 最后一条语句给出正确的结果:印象数“ 34,017”。 When I remove it and include the CSV.open statement below I get the error that follows. 当我删除它并在下面包含CSV.open语句时,我得到以下错误。 Line 87 begins: csv << 第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)

I am running Ruby 1.9.2 and appreciate any advice you have. 我正在运行Ruby 1.9.2,感谢您的任何建议。

With the mysql gem (mysql2 is different) you can only iterate through a mysql result set with each_hash once: after a row has been consumed mysql no longer returns it to you because it thinks you are done with it. 使用mysql gem(mysql2是不同的),您只能使用each_hash遍历mysql结果集一次:在消耗each_hash一行之后,mysql不再将其返回给您,因为它认为您已经完成了它。 Your first call to each_hash consumes all the rows, so when you iterate through it a second time there are no rows left and you get no output. 第一次调用each_hash会消耗所有行,因此第二次进行遍历时,将没有行,也没有输出。

If you remove your puts version of the output it should work 如果删除输出的puts版本,则应该可以使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM