Created
October 7, 2016 02:35
-
-
Save dineshprabu-freshdesk/5e5c4ef3814893bbbd8883e6b044f218 to your computer and use it in GitHub Desktop.
Loading Multiple CSV Files 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
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