0

I want script save results into .csv or .txt file. My script must perform select into mssql database and send all strings from this request on email. My code:

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

My problem:

The generated csv file contains only the first line of my request. How can I write to a file all the strings of my request?

1
  • 1
    you need to put the results.each loop into the CSV.open block Commented Feb 9, 2017 at 10:08

2 Answers 2

1

How about this? CSV creation outside the results loop.

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
Sign up to request clarification or add additional context in comments.

2 Comments

I get an error when so doing: C:/Ruby23/lib/ruby/2.3.0/csv.rb:1675:in <<': undefined method map' for nil:NilClass (NoMethodError)
I have updated the example with ".to_a" on row, which I suspect might be the reason.
0

You seem to already have a matrix inside results. So, instead of this:

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

all you need is to convert a matrix to the array of arrays and feed it to CSV:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.