Home >Database >Mysql Tutorial >How can I batch import multiple CSV files into MySQL efficiently?

How can I batch import multiple CSV files into MySQL efficiently?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-02 06:40:02757browse

How can I batch import multiple CSV files into MySQL efficiently?

Batch Importing Multiple CSV Files into MySQL

Importing multiple CSV files into a MySQL database can be a time-consuming task when done manually. This article provides a solution for batch importing CSV files, significantly reducing the manual effort required.

Using a Shell Script for Batch Importing

One efficient way to import multiple CSV files is by utilizing a shell script. Here's an example script that you can modify to suit your environment:

#!/usr/bin/env bash
cd yourdirectory

for f in *.csv
do
        mysql -e "USE yourDatabase LOAD DATA LOCAL INFILE '"$f"'INTO TABLE yourtable"
done

Explanation of the Script:

  • cd yourdirectory: Navigate to the directory where your CSV files are located.
  • for f in *.csv: This loop iterates through all files with the .csv extension in the current directory.
  • mysql -e "USE yourDatabase LOAD DATA LOCAL INFILE '"$f"'INTO TABLE yourtable": This command uses the mysql command-line utility to import each file into a table named yourtable in the database named yourDatabase.

Usage:

To use this script, follow these steps:

  1. Save the script in a file with a .sh extension.
  2. Make the script executable by running chmod x import_csv.sh.
  3. Run the script from the command line: ./import_csv.sh.

This script will automatically import all the CSV files in the current directory into the specified database and table.

The above is the detailed content of How can I batch import multiple CSV files into MySQL efficiently?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn