Skip to content

Instantly share code, notes, and snippets.

@pigoz
Created May 31, 2011 13:04
Show Gist options
  • Save pigoz/1000465 to your computer and use it in GitHub Desktop.
Save pigoz/1000465 to your computer and use it in GitHub Desktop.
Ruby SQL to CSV exporter
require "rubygems"
begin
require 'sequel'
rescue LoadError
puts "Please run gem install sequel"
exit!
end
DB = Sequel.connect(:adapter => 'mysql2',
:host => '127.0.0.1',
:database => '???',
:user => '???',
:password => '???')
Dir['export/*.csv'].each { |f| File.delete(f); puts "deleted: #{f}" }
class CVSSQLExporter
def initialize(filename, db, sql)
@filename = File.join('export', filename)
@db = db
@sql = sql
end
def export()
require 'csv'
CSV.open(@filename, 'wb') do |csv|
first = true
@db[@sql].all.each do |row|
csv << row.inject([]) { |r, n| r << n[0] } and first = false if first
csv << row.inject([]) { |r, n| r << n[1] }
end
end
puts "exported: #{@filename}"
end #/def export
end
foo_sql = <<-SQL
select *
from bar as foo
SQL
CVSSQLExporter.new('foo.csv', DB, foo_sql).export
@hgundi
Copy link

hgundi commented Oct 4, 2020

Thanks a ton.This is really useful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment