Reputation: 21851
I'm trying to query a table, fetch all records, and save the result as a CSV file. This is what I've done so far:
require 'OCI8'
conn = OCI8.new('scott','tiger','020')
file = File.open('output.csv','w') do |f|
conn.exec('select * from emp') do |e|
f.write log.join(',')
end
end
.. And while it does generate a CSV file, the problem is that all records get saved onto a single line. How can I put the data such that each record goes onto a new line ?
Upvotes: 1
Views: 1196
Reputation: 44090
Well, you can use f.puts
instead of f.write
there, but I'd recommend you take a look at CSV
module:
http://ruby-doc.org/stdlib/libdoc/csv/rdoc/index.html
outfile = File.open('csvout', 'wb')
CSV::Writer.generate(outfile) do |csv|
csv << ['c1', nil, '', '"', "\r\n", 'c2']
...
end
outfile.close
PS: Actually, there is another CSV library called FasterCSV, which became CSV
in standard library in Ruby 1.9. But in general, any should be better than writing it yourself.
Upvotes: 2