Home  >  Article  >  Database  >  How to Batch Import Multiple CSV Files into a MySQL Database Using a Shell Script?

How to Batch Import Multiple CSV Files into a MySQL Database Using a Shell Script?

DDD
DDDOriginal
2024-11-01 12:18:02161browse

How to Batch Import Multiple CSV Files into a MySQL Database Using a Shell Script?

Seamlessly Importing Multiple CSV Files into a MySQL Database

Importing several CSV files into a MySQL database can be a tedious task when done manually. Fortunately, there is an automated solution to handle this efficiently.

How to Batch Import CSV Files Using a Shell Script

Follow these steps to effortlessly import multiple CSV files into your MySQL database:

  1. Create a Shell Script:

    Create a shell script file with a .sh extension. The following code can be used as a template:

    <code class="bash">#!/usr/bin/env bash
    cd yourdirectory
    for f in *.csv
    do
            mysql -e "USE yourDatabase LOAD DATA LOCAL INFILE '"$f"'INTO TABLE yourtable"
    done</code>

    Replace "yourdirectory" with the directory containing your CSV files, "yourDatabase" with the target MySQL database name, and "yourtable" with the table you wish to import into.

  2. Execute the Script:

    Navigate to the directory where the shell script is located and execute it using the following command:

    <code class="bash">chmod +x import_csv.sh
    ./import_csv.sh</code>
  3. Enjoy the Automatic Imports:

    The shell script will loop through all CSV files in the specified directory and import them into the designated MySQL database and table. You can monitor the progress by observing the command line output.

Additional Tips:

  • Ensure MySQL is running and accessible before executing the script.
  • If any errors occur during the import process, check the MySQL error logs for insights.
  • Consider using a data import tool like MySQL Workbench to import large CSV files more efficiently.

The above is the detailed content of How to Batch Import Multiple CSV Files into a MySQL Database Using a Shell Script?. 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