Created
May 12, 2011 07:31
-
-
Save rjungemann/968095 to your computer and use it in GitHub Desktop.
Load a spreadsheet exported as CSV into MySQL
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
#!/usr/bin/env ruby | |
# USAGE: | |
# caramelize mysql://root:root@localhost:8889/sample samples sample.csv | |
require 'csv' | |
require 'mysql' | |
require 'sequel' | |
def sluggerize string | |
str = string.downcase.gsub(/[^\w]/, "_").gsub(/__+/, "_") | |
str = str[1..-1] while str[0] == "_" | |
str = str[0..-2] while str[-1] == "_" | |
str | |
end | |
db_string, table_name, csv_path = *ARGV | |
raise "database connection string not provided." if db_string.nil? | |
raise "table name not provided." if table_name.nil? | |
headings, db, table = nil, nil, nil | |
CSV.foreach(csv_path) do |row| | |
if headings.nil? | |
headings = row.map { |item| sluggerize item } | |
db = Sequel.connect(db_string) | |
begin | |
DB.create_table table_name do | |
primary_key :id | |
headings.each { |heading| String heading } | |
end | |
rescue Exception => e | |
puts e.inspect | |
end | |
table = db[table_name] | |
else | |
attributes = {} | |
headings.each_with_index { |heading, index| attributes[heading] = row[index] } | |
table.insert attributes | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment