Skip to content

Instantly share code, notes, and snippets.

@rjungemann
Created May 12, 2011 07:31
Show Gist options
  • Save rjungemann/968095 to your computer and use it in GitHub Desktop.
Save rjungemann/968095 to your computer and use it in GitHub Desktop.
Load a spreadsheet exported as CSV into MySQL
#!/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