Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dineshprabu-freshdesk/5e5c4ef3814893bbbd8883e6b044f218 to your computer and use it in GitHub Desktop.
Save dineshprabu-freshdesk/5e5c4ef3814893bbbd8883e6b044f218 to your computer and use it in GitHub Desktop.
Loading Multiple CSV Files into MySql
require 'mysql' # gem install mysql
require 'csv'
db_name = "" # Database Name
db_connection = Mysql.new("localhost","root","","#{db_name}") # Change the creds, if needed.
csv_files = Dir["*.csv"] # Script goes to the current directory of the csv files.
csv_files.each do |csv_file|
headers = (CSV.read csv_file)[0]
db_connection.query "CREATE TABLE IF NOT EXISTS #{csv_file.split('.')[0]}("+headers.map{|c| "`#{c}` TEXT"}.join(',')+")"
p "table created for #{csv_file} "
db_connection.query "LOAD DATA LOCAL INFILE '#{csv_file}' INTO TABLE #{csv_file.split('.')[0]} FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\n' IGNORE 1 ROWS"
p "and Data imported."
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment