Created
November 26, 2014 23:35
-
-
Save cvengros/32ad1a518b3956617522 to your computer and use it in GitHub Desktop.
Export table to CSV
This file contains hidden or 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' | |
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