tags:

views:

50

answers:

1

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 ?

+2  A: 

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.

Mladen Jablanović
Sathya
I don't understand your question, what do you mean by "separate value". As I see from OCI8 docs, `e` in your block is already an array, and you can write it to CSV row using `csv << e`.
Mladen Jablanović
Thanks for the help, I got it done!
Sathya