0

When I try to create a CSV file from a MySQL DB using ruby no file is created and no error is returned. This is on a Windows 10 machine.

Here is my code:

def dump_csv
    Dir.mkdir 'C:\temp'  unless File.exists? 'C:\temp'
    <<-SQL
        SELECT *
        FROM #{@table}
        GROUP BY a, b, c, d
        HAVING COUNT(*) < 40
        INTO OUTFILE 'C:\\\\temp\\\\temp.csv'
        FIELDS TERMINATED BY ','
    SQL
end

I know it's not a permission error, because if I input that statement into MySQL directly it works just fine. Any ideas? Or another way of going about it?

Thanks!

ChrisD
  • 109
  • 10
  • http://stackoverflow.com/q/2774808 – Drew Nov 10 '15 at 19:05
  • I've tried a bunch of slash, none work. I'm pretty sure it should be '\\\\', but I've tried up to 8 slashes, no go... – ChrisD Nov 10 '15 at 19:08
  • how about going the other bizarro way as seen http://stackoverflow.com/q/7173000 – Drew Nov 10 '15 at 19:10
  • good thought, but no go unfortunately. – ChrisD Nov 10 '15 at 19:16
  • I think your sql statement should be `INTO OUTFILE 'C:\temp\temp.csv'`. And as others pointed out, you shouldn't use forward slashes in paths on any OS anyway, so you should write: `INTO OUTFILE 'C:/temp/temp.csv'`--and then it doesn't matter if you use single quotes or double quotes because there are no escape sequences in the string. – 7stud Nov 10 '15 at 20:01
  • I've tried this as well with no success. – ChrisD Nov 10 '15 at 20:14
  • How do you connect to MySQL with ruby ? – Renaud Kern Nov 11 '15 at 09:00

2 Answers2

0

I have only taken a quick glance at this, but may switch out File.exists? for Dir.exists? since you are trying to create a directory and are checking if a FILE exists. I would map it out a little more clearer to something similar to this:

def temp_file
  temp_directory = 'C:\temp'
  Dir.mkdir(temp_directory) unless Dir.exists?(temp_directory)
  file = "#{temp_directory}/temporary_csv.csv"
end
File.open(temp_file, 'w') << SQL
sclem72
  • 466
  • 6
  • 16
0

You are not executing the SQL.

the construct

<<-SQL
  ...
SQL

is just constructing a string with "SQL" as end marker

Meier
  • 3,858
  • 1
  • 17
  • 46