How To Import A MySQL Database

Do you want to import a MySQL database? The article will show you step by step-by-step how to import a MySQL database with command line.

database image

Note: this article assumes you already have a MySQL database setup and a MySQL username setup. If you don’t have those, you can read this article about how to setup a MySQL database  and this article for how to setup a MySQL username.

This article will focus on import a mysql database in Linux but the steps should work in other operating systems like Windows and Mac as well.

Maybe you have a site running WordPress or another CMS using MySQL. Knowing how to import a MySQL database is incredibly useful to know.

Here are some reasons for wanting to import a database:
1. You are changing web hosts or changing to a VPS and you want to use the same database as before.
2. You just backed up your database but want to recreate it somewhere else. For example, I created a web app that uses MySQL as it’s database and I want the database to be on my my own home computer and on my server.

Now for the actual steps…

How To Import A MySQL Database In Linux

The way to import a MySQL database in Linux is as follows using the mysql command:

mysql -u username -p database_name_to_import_into < databasefile.sql

The username part of the above comand is the MySQL username which has permission over the database, the database_name_to_import_into is the actual database that you want to import into. The -p flag means you will give a password (you will manually type in your password after typing the above command), and the databasefile.sql is the file which actually has all of the database data that you want to import.

As a quick note, in Bash, there are different redirection operators. The ‘>‘ character redirects standard output to a file, and the ‘<‘ character redirects standard input to a command. Read more about those characters here and here

An Example Of How To Import MySQL Database

Let's say I had a backed up database file called databasebackup.sql, the database name was sampledatabase, and the MySQL username were sampleuser. To import the databasebackup.sql file into the sampledatabase database, the command one would use would be like the following:

mysql -u sampleuser -p sampledatabase < databasebackup.sql

You won’t see any output besides a prompt for entering your MySQL password if it is successful. Though if something is wrong, you will see an error message.

Make sure the databasebackup.sql file is in the current directory you are using or adjust appropriately to the location of the sql file.

An example of importing a MySQL database.
An example of importing a MySQL database.

Did you find this article about How To Import A MySQL Database useful? If so, please share it with your friends.

2 thoughts on “How To Import A MySQL Database”

Leave a Reply

Your email address will not be published. Required fields are marked *