Created
May 31, 2011 13:04
-
-
Save pigoz/1000465 to your computer and use it in GitHub Desktop.
Ruby SQL to CSV exporter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks a ton.This is really useful