Table of contents

How do I import a .sql file via the command-line?

Author:

Published:

Updated on August 15, 2024

Reading Time: 1 min read

If you’ve set up SSH access for a package, you can use one of two methods to import a MySQL database via the command line. Please refer to our guide on how to connect to your package via SSH if needed.

MySQL CLI #

To import a SQL file via the command line, you can use the mysql command. Here’s how:

mysql -h hostname -u username -p database_name < file.sql

  • Replace hostname with your database server name.
  • Replace username with your database username.
  • Replace database_name with the name of the database where you want to import the SQL file.
  • Replace file.sql with the path to the SQL file you want to import.

After entering the command, you’ll be prompted to enter the password for the specified username. Enter the correct password, and the import process will begin.

Note: Make sure the SQL file contains valid SQL commands and is in the correct format for the database you’re using. If the import is successful, the data from the file will be imported into the specified database.

Compressed Files #

If the database file is zipped, you’ll need to unzip it first.

  • For a .zip file, you can use the unzip command:

unzip databasefile.sql.zip

For a .gz file, you can use the gunzip command:

gunzip databasefile.sql.gz

After unzipping, you can proceed to import the unzipped file as normal.

WP CLI
To import a SQL file using the WP-CLI tool, follow these steps. WP-CLI is a command-line tool for managing WordPress installations, and it includes a command for importing databases.

Navigate to Your WordPress Installation:

SSH into your package and navigate to the root directory of your WordPress installation.
Backup Your Current Database (optional but recommended):

It's a good practice to create a backup of your existing database before performing an import. Use the following WP-CLI command to export your database:

wp db export

This command will create a SQL dump of your database in the WordPress installation folder. You can use it as a backup in case anything goes wrong.
Import the SQL File:

Use the wp db import command to import the SQL file. Here's the command:

wp db import file.sql

Verify the Import:

After the import is complete, verify by checking your WordPress site to ensure that the data from the SQL file has been imported correctly.
You've successfully imported an SQL file into your WordPress database using WP-CLI. This method is especially useful for migrating WordPress sites or importing data into a new WordPress installation.