将数组写入csv文件

时间:2017-02-09 09:59:51

标签: ruby-on-rails arrays sql-server ruby csv

我希望脚本保存结果为.csv或.txt文件。我的脚本必须执行select into mssql database并在电子邮件中发送此请求的所有字符串。 我的代码:

require 'tiny_tds'
require 'csv'

@db_host  = 'myserver.com'
@db_user  = 'mylogin'
@db_pass  = 'mypassword'
client = TinyTds::Client.new(:host => @db_host, :username => @db_user, :password => @db_pass)
results = client.execute("    SELECT * FROM mydatabase    ")

results.each do |row|
p $rows = row.to_a

p h = $rows
CSV.open("data.csv", "wb") {|csv| h.to_a.each {|elem| csv << elem} }
end

我的问题:

生成的csv文件仅包含我请求的第一行。如何将所有请求的字符串写入文件?

2 个答案:

答案 0 :(得分:0)

您似乎已在results内部有一个矩阵。所以,而不是:

results.each do |row|
  rows = row.to_a
  CSV.open("data.csv", "wb") do |csv|
    rows.to_a.each { |elem| csv << elem}
  end
end

您只需将矩阵转换为数组数组并将其提供给CSV

results.map! { |row| row.to_a.map(&:to_a) }
CSV.open("data.csv", "wb") { |csv| csv.replace results }

答案 1 :(得分:0)

这个怎么样?在结果循环外创建CSV。

require 'tiny_tds'
require 'csv'

db_host  = 'myserver.com'
db_user  = 'mylogin'
db_pass  = 'mypassword'
client = TinyTds::Client.new(:host => db_host, :username => db_user, :password => db_pass)
results = client.execute("SELECT * FROM mydatabase")

CSV.open("data.csv", "wb") do |csv|
  results.each do |row|
    csv << row.to_a
  end
end