Skip to content

Instantly share code, notes, and snippets.

@cvengros
Created November 26, 2014 23:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cvengros/32ad1a518b3956617522 to your computer and use it in GitHub Desktop.
Save cvengros/32ad1a518b3956617522 to your computer and use it in GitHub Desktop.
Export table to CSV
require 'rubygems'
require 'jdbc/dss'
require 'sequel'
require 'csv'
Jdbc::DSS.load_driver
FILENAME = ''
USERNAME = ''
PASSWORD = ''
JDBC_URL = ''
TABLE_NAME = ''
CSV.open(FILENAME, 'wb', :force_quotes => true) do |csv|
Sequel.connect JDBC_URL, :username => USERNAME, :password => PASSWORD do |conn|
# get the names of cols
columns = []
conn.fetch "SELECT column_name FROM columns WHERE table_name = '#{TABLE_NAME}'" do |row|
columns.push(row[:column_name])
end
# write header
csv << columns
sql = "SELECT * FROM #{TABLE_NAME}"
# get the keys for columns, stupid sequel
col_keys = nil
conn.fetch "#{sql} LIMIT 1" do |row|
col_keys = row.keys
end
# go through the table write to csv
conn.fetch sql do |row|
csv << row.values_at(*col_keys)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment