· 9 years ago · Oct 07, 2016, 08:10 AM
1require 'mysql' # gem install mysql
2require 'csv'
3
4db_name = "" # Database Name
5db_connection = Mysql.new("localhost","root","","#{db_name}") # Change the creds, if needed.
6csv_files = Dir["*.csv"] # Script goes to the current directory of the csv files.
7csv_files.each do |csv_file|
8 headers = (CSV.read csv_file)[0]
9 db_connection.query "CREATE TABLE IF NOT EXISTS #{csv_file.split('.')[0]}("+headers.map{|c| "`#{c}` TEXT"}.join(',')+")"
10 p "table created for #{csv_file} "
11 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"
12 p "and Data imported."
13end