Created
November 27, 2019 20:31
-
-
Save ChrisTaylorDeveloper/6813068ec7ecbf9b75bd34a87ec7b749 to your computer and use it in GitHub Desktop.
Dynamically create a mysql table to accomodate a csv file and import the csv file.
This file contains 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
#!/bin/bash | |
# Contents of create-table.sql | |
# | |
# CREATE TABLE `csv` ( | |
# `id` int(11) NOT NULL AUTO_INCREMENT, | |
# PRIMARY KEY (`id`) | |
# ); | |
mysql -u user -ppassword < create-table.sql | |
# Read column headers into an array. | |
IFS=',' read -ra COLS <<< $(head -n1 file.csv) | |
# Loop through the array and create a | |
# new table column for each csv column. | |
for COL in "${COLS[@]}"; do | |
mysql -u user -ppassword -e "ALTER TABLE csv ADD \`$COL\` TEXT DEFAULT NULL;" | |
done | |
# Contents of load-csv-into-table.sql | |
# | |
# LOAD DATA LOCAL INFILE 'file.csv' | |
# INTO TABLE `csv` | |
# FIELDS TERMINATED BY ',' ENCLOSED BY '"' | |
# LINES TERMINATED BY '\n' | |
# IGNORE 1 ROWS; | |
mysql -u user -ppassword < load-csv-into-table.sql |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment