Operation MySQL Database in CentOS 7
1. How to Manage MySQL Databases and Users from the Command Line
Before you begin
Before you start with this tutorial, we are assuming that you already have MySQL or MariaDB server installed on your system. All commands will be executed as a root user.
To open the MySQL prompt, type the following command and enter the MySQL root user password when prompted:
mysql -u root -p
1)Create a new MySQL database
To create a new MySQL database run the following command, just replace database_name with the name of the database that you want to create:
CREATE DATABASE database_name;
Query OK, 1 row affected (0.00 sec)
If you try to create a database that already exists you will see the following error message:
ERROR 1007 (HY000): Can't create database 'database_name'; database exists
To avoid errors if the database with the same name as you are trying to create exists you can use the following command:
CREATE DATABASE IF NOT EXISTS database_name;
Query OK, 1 row affected, 1 warning (0.00 sec)
In the output above, Query OK means that the query was successful, and 1 warning tells us that the database already exists and no new database was created.
2)List all MySQL databases
You can list all databases that exist on our MySQL or MariaDB server with the following command:
SHOW DATABASES;
The output will look something like this:
+--------------------+
| Database |
+--------------------+
| information_schema |
| database_name |
| mysql |
| performance_schema |
| sys |
+--------------------+
5 rows in set (0.00 sec)
The information_schema, mysql, performance_schema, and sys databases are created at installation time and they are storing information about all other databases, system configuration, users, permission and other important data. These databases are necessary for the proper functionality of the MySQL installation.
3)Delete a MySQL database
Deleting a MySQL database is as simple as running a single command. This is a non-reversible action and should be executed with caution. Make sure that you are not removing a wrong database, as once you delete the database it cannot be recovered.
To delete a MySQL or MariaDB, database run the following command:
DROP DATABASE database_name;
Query OK, 0 rows affected (0.00 sec)
If you try to delete a database that doesn’t exist you will see the following error message:
ERROR 1008 (HY000): Can't drop database 'database_name'; database doesn't exist
To avoid this error you can use the following command:
DROP DATABASE IF EXISTS database_name;
4)Create a new MySQL user account
A user account in MySQL consists of a user name and host name parts.
To create a new MySQL user account run the following command, just replace ‘database_user’ with the name of the user that you want to create:
CREATE USER 'database_user'@'localhost' IDENTIFIED BY 'user_password';
In the command above we have set the hostname part to localhost which means that this user will be able to connect to the MySQL server only from the localhost ( i.e from the system where MySQL Server runs). If you want to grant access from another host(s) just change the localhost with the remote machine IP or use '%' wildcard for the host part, which means that the user account will be able to connect from any host.
Same as when working with the databases to avoid an error when trying to create a user account which already exists you can use:
CREATE USER IF NOT EXISTS 'database_user'@'localhost' IDENTIFIED BY 'user_password';
Query OK, 0 rows affected, 1 warning (0.00 sec)
4)Change a MySQL user account password
The syntax for changing a MySQL or MariaDB user account password depends on the server version you are running on your system.
You can find your server version by issuing the following command:
mysql --version
If you have MySQL 5.7.6 and newer or MariaDB 10.1.20 and newer, to change the password use the following command:
ALTER USER 'database_user'@'localhost' IDENTIFIED BY 'new_password';
If you have MySQL 5.7.5 and older or MariaDB 10.1.20 and older, then use:
SET PASSWORD FOR 'database_user'@'localhost' = PASSWORD('new_password');
In both cases, the output should look like this:
Query OK, 0 rows affected (0.00 sec)
5)List all MySQL user accounts
You can list all MySQL or MariaDB user accounts by querying the mysql.users table:
SELECT user, host FROM mysql.user;
The output should look similar to below:
+------------------+-----------+
| user | host |
+------------------+-----------+
| database_user | % |
| database_user | localhost |
| debian-sys-maint | localhost |
| mysql.session | localhost |
| mysql.sys | localhost |
| root | localhost |
+------------------+-----------+
6 rows in set (0.00 sec)
6)Delete MySQL user account
To delete a user account , use the following command:
DROP USER 'database_user@'localhost';
If you try to delete a user account which doesn’t exist an error will occur.
ERROR 1396 (HY000): Operation DROP USER failed for 'database_user'@'localhost'
Same as when working with the databases to avoid the error you can use:
DROP USER IF EXISTS 'database_user'@'localhost';
Query OK, 0 rows affected, 1 warning (0.00 sec)
7)Grant permissions to a MySQL user account
There are multiple types of privileges that can be granted to a user account. You can find a full list of privileges supported by MySQL here . In this guide we will go through several examples:
To grand all privileges to a user account over a specific database, use the following command:
GRANT ALL PRIVILEGES ON database_name.* TO 'database_user'@'localhost';
To grand all privileges to a user account over all databases, use the following command:
GRANT ALL PRIVILEGES ON *.* TO 'database_user'@'localhost';
To grand all privileges to a user account over a specific table from a database, use the following command:
GRANT ALL PRIVILEGES ON database_name.table_name TO 'database_user'@'localhost';
If you want to grant only specific privileges to a user account over a specific database type:
GRANT SELECT, INSERT, DELETE ON database_name.* TO database_user@'localhost';
8)Revoke permissions from a MySQL user account
If you need to revoke one or more privileges or all privileges from a user account, the syntax is almost identical to granting it. For example, if you want to revoke all privileges from a user account over a specific database, use the following command:
REVOKE ALL PRIVILEGES ON database_name.* TO 'database_user'@'localhost';
9)Display MySQL user account privileges
To find the privilege(s) granted to a specific MySQL user account type:
SHOW GRANTS FOR 'database_user'@'localhost';
+---------------------------------------------------------------------------+
| Grants for database_user@localhost |
+---------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'database_user'@'localhost' |
| GRANT ALL PRIVILEGES ON `database_name`.* TO 'database_user'@'localhost' |
+---------------------------------------------------------------------------+
2 rows in set (0.00 sec)
Conclusion
This tutorial covers only the basics, but it should be a good starting for anyone who wants to learn how to manage MySQL databases and users from the command line. You can also check the tutorial about how to reset a MySQL root password in case you have forgotten it.
2. How to Reset the MySQL Root Password
Too many password to remember? forgotten our MySQL root password? Don’t worry, it happens to all of us.
In this article, we will show you how to reset the MySQL root password from the command line.
1)Identify the Server Version
Depending on the MySQL or MariaDB server version you are running on your system, you will need to use different commands to recover the root password.
You can find your server version by issuing the following command:
mysql --version
If you have MySQL installed in your system the output will look something like this:
mysql Ver 14.14 Distrib 5.7.22, for Linux (x86_64) using EditLine wrapper
Or output like this for MariaDB:
mysql Ver 15.1 Distrib 10.1.33-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2
Be sure to make a note of which version of MySQL or MariaDB you’re running.
2)How to Reset MySQL or MariaDB Root Password
Follow these steps to reset your MySQL/MariaDB root password:
1. Stop the MySQL/MariaDB service
To change the root password first, you need to stop the MySQL server. To do so type the following command:
sudo systemctl stop mysql
2. Start the MySQL/MariaDB server without loading the grant tables
Start the database server without loading the grant tables:
sudo mysqld_safe --skip-grant-tables &
The ampersand & at the end of the command above will cause the program to run in the background, so you can continue to use the shell.
When the
--skip-grant-tables
option is used, anyone can to connect to the database server without a password and with all privileges granted.
3. Log in to the MySQL shell
Now you can connect to the database server as the root user:
mysql -u root
4. Set a new root password
- Run the following commands if you run MySQL 5.7.6 and later or MariaDB 10.1.20 and later:
ALTER USER 'root'@'localhost' IDENTIFIED BY 'MY_NEW_PASSWORD';FLUSH PRIVILEGES;
If ALTER USER statement doesn’t work for you, try to modify the user table directly:
UPDATE mysql.user SET authentication_string = PASSWORD('MY_NEW_PASSWORD')
WHERE User = 'root' AND Host = 'localhost';
FLUSH PRIVILEGES;
Run the following commands if you have MySQL 5.7.5 and earlier or MariaDB 10.1.20 and earlier:
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('MY_NEW_PASSWORD');
FLUSH PRIVILEGES;
In both cases if all goes well, you should see the following output:
Query OK, 0 rows affected (0.00 sec)
5. Stop and Start the database server normally
Now that the root password is set, stop the database server and start it normally:
mysqladmin -u root -p shutdown
You will be prompted to enter the new root password.
Start the database server normally:
For MySQL, type:
sudo systemctl start mysql
For MariaDB, type:
sudo systemctl start mariadb
6. Verify the password
To verify that the new root password has been applied correctly, type:
mysql -u root -p
You will be prompted to enter the new root password. Enter it, and you should be logged in to your database server.
Conclusion
We’ve shown you how to reset your MySQL/MariaDB root password. Make sure your new root password is strong and secure and keep it in a safe place.
The instructions in this guide should work with any modern Linux distribution such as Ubuntu 18.04, Debian 10 and CentOS 8.
3. How to Create and Select MySQL Databases
MySQL is the most popular open-source relational database management system.
This tutorial explains how to create MySQL or MariaDB databases through the command line.
Before you begin
We are assuming that you already have MySQL or MariaDB server installed on your system.
All commands are executed as an administrative user (the minimum privilege required to create a new database is CREATE) or with a root account.
To access the MySQL shell type the following command and enter your MySQL root user password when prompted:
mysql -u root -p
If you haven’t set a password for your MySQL root user, you can omit the -p option.
Create a MySQL Database
Creating a new MySQL database is as simple as running a single command.
To create a new MySQL or MariaDB database issue the following command, where database_name is the name of the database you want to create:
CREATE DATABASE database_name;
Query OK, 1 row affected (0.00 sec)
If you try to create a database that already exists, you will see the following error message:
ERROR 1007 (HY000): Can't create database 'database_name'; database exists
To avoid errors if the database with the same name as you are trying to create exists, use the IF NOT EXISTS statement:
CREATE DATABASE IF NOT EXISTS database_name;
Query OK, 1 row affected, 1 warning (0.00 sec)
In the output above, Query OK means that the query was successful, and 1 warning tells us that the database already exists, and no new database was created.
On Linux, MySQL database and table names are case sensitive.
View All MySQL Databases
To view the database you’ve created, from within the MySQL shell, execute the following command:
SHOW DATABASES;
The command above will print a list of all databases on the server. The output should be similar to this:
+--------------------+
| Database |
+--------------------+
| information_schema |
| database_name |
| mysql |
| performance_schema |
| test |
+--------------------+
5 rows in set (0.00 sec)
Select a MySQL Database
When you create a database, the new database is not selected for use.
To select a database before you begin a MySQL session, use the following statement:
USE database_name;
Database changed
Once you select a database, all the subsequent operations, such as creating tables, are performed on the selected database.
Each time you want to work on a database, you must select it with the USE statement.
You can also select the database when connecting to the MySQL server by appending the name of the database at the end of the command:
mysql -u root -p database_name
Create a MySQL Database with mysqladmin
You can also use the mysqladmin utility to create a new MySQL database from the Linux terminal.
For example, to create a database named database_name, you would use the following command:
mysqladmin -u root -p create database_name
Conclusion
We have shown you how to create and select MySQL databases using the MySQL shell and mysqladmin command.
4. How to Create MySQL Users Accounts and Grant Privileges
MySQL is the most popular open-source relational database management system. MySQL server allows us to create numerous user accounts and grant appropriate privileges so that the users can access and manage databases.
This tutorial describes how to create MySQL user accounts and grant privileges.
Before you Begin
We are assuming that you already have MySQL or MariaDB server installed on your system.
All commands are executed inside the MySQL shell as root or administrative user. The minimum privileges required to create user accounts and define their privileges is CREATE USER and GRANT.
To access the MySQL shell type the following command and enter your MySQL root user password when prompted:
mysql -u root -p
If you have MySQL version 5.7 or later that uses the auth_socket plugin login as root by typing:
sudo mysql
Create a new MySQL User Account
A user account in MySQL consists of two parts: user name and host name.
To create a new MySQL user account, run the following command:
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'user_password';
Replace newuser with the new user name, and user_password with the user password.
In the example above, the hostname part is set to localhost, which means that the user will be able to connect to the MySQL server only from the localhost (i.e. from the system where MySQL Server runs).
To grant access from another host, change the hostname part with the remote machine IP. For example, to grant access from a machine with IP 10.8.0.5 you would run:
CREATE USER 'newuser'@'10.8.0.5' IDENTIFIED BY 'user_password';
To create a user that can connect from any host, use the '%' wildcard as a host part:
CREATE USER 'newuser'@'%' IDENTIFIED BY 'user_password';
Grant Privileges to a MySQL User Account
There are multiple types of privileges that can be granted to a user account. You can find a full list of privileges supported by MySQL here .
The most commonly used privileges are:
- ALL PRIVILEGES – Grants all privileges to a user account.
- CREATE – The user account is allowed to create databases and tables.
- DROP - The user account is allowed to drop databases and tables.
- DELETE - The user account is allowed to delete rows from a specific table.
- INSERT - The user account is allowed to insert rows into a specific table.
- SELECT – The user account is allowed to read a database.
- UPDATE - The user account is allowed to update table rows.
To grant specific privileges to a user account, use the following syntax:
GRANT permission1, permission2 ON database_name.table_name TO 'database_user'@'localhost';
Here are some examples:
Grand all privileges to a user account over a specific database:
GRANT ALL PRIVILEGES ON database_name.* TO 'database_user'@'localhost';
Grand all privileges to a user account on all databases:
GRANT ALL PRIVILEGES ON *.* TO 'database_user'@'localhost';
Grand all privileges to a user account over a specific table from a database:
GRANT ALL PRIVILEGES ON database_name.table_name TO 'database_user'@'localhost';
Grant multiple privileges to a user account over a specific database:
GRANT SELECT, INSERT, DELETE ON database_name.* TO database_user@'localhost';
Display MySQL User Account Privileges
To find the privilege(s) granted to a specific MySQL user account, use the SHOW GRANTS statement:
SHOW GRANTS FOR 'database_user'@'localhost';
The output will look something like below:
+---------------------------------------------------------------------------+
| Grants for database_user@localhost |
+---------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'database_user'@'localhost' |
| GRANT ALL PRIVILEGES ON `database_name`.* TO 'database_user'@'localhost' |
+---------------------------------------------------------------------------+
2 rows in set (0.00 sec)
Revoke Privileges from a MySQL User Account
The syntax to revoke one or more privileges from a user account is almost identical as when granting privileges.
To revoke all privileges from a user account over a specific database, run the following command:
REVOKE ALL PRIVILEGES ON database_name.* FROM 'database_user'@'localhost';
Remove an Existing MySQL User Account
To delete a MySQL user account use the DROP USER statement:
DROP USER 'user'@'localhost'
The command above will remove the user account and its privileges.
Conclusion
This tutorial covers only the basics, but it should be a good starting for anyone who wants to learn how to create new MySQL user accounts and grant privileges.
If you have any questions or feedback, feel free to leave a comment.
5. How to Show/List Users in MySQL
Have you ever needed to get a list of all users in your MySQL server? There are commands to show databases and tables, but there is no MySQL show users command.
This tutorial explains how to list all user accounts in a MySQL database server through the command line. We’ll also show you how the find out which users have access to a given database.
Before You Begin
We are assuming that you already have MySQL or MariaDB server installed on your system.
All commands are executed inside the MySQL shell as a root user. To access the MySQL shell type the following command and enter your MySQL root user password when prompted:
mysql -u root -p
If you haven’t set a password for your MySQL root user, you can omit the -p option.
Show All MySQL Users
MySQL stores information about the users in a table named user in the mysql database.
To get a list of all MySQL user accounts, use the SELECT statement to retrieve all rows from the mysql.users table:
SELECT User, Host FROM mysql.user;
The output should look similar to below:
+------------------+-----------+
| user | host |
+------------------+-----------+
| root | localhost |
| luke | % |
| yoda | % |
| jabba | 10.10.0.6 |
| jabba | 10.10.0.9 |
| chewbacca | localhost |
| leia | localhost |
| han | localhost |
+------------------+-----------+
8 rows in set (0.00 sec)
The command above shows only two columns from the mysql.user table (User and Host), This table contains more than 40 columns such as Password, Select_priv, Update_priv, etc.
A user account in MySQL consists of two parts: a user name and hostname.
Use the desc mysql.user; statement to display information about the table’s columns. Once you know the column name, you can run a query against a selected data.
For example, to get a list of all MySQL users accounts including information about the password and whether it is active or expired, you would use the following query:
SELECT User, Host, Password, password_expired FROM mysql.user;
+----------------+-----------+-------------------------------------------+------------------+
| User | Host | Password | password_expired |
+----------------+-----------+-------------------------------------------+------------------+
| root | localhost | | N |
| luke | % | *ADC3B5B27617732CD6320A2DA976258E149A7EC8 | N |
| yoda | % | *9550E004046348198A143A115550E1262209FB6F | N |
| jabba | 10.10.0.6 | *F91C86B486B945C083B61A05FF6E197560D187EC | Y |
| jabba | 10.10.0.9 | | Y |
| chewbacca | localhost | *17F2B1E48029294841AD66772BEBB7E6E6A005AF | N |
| leia | localhost | *74409C8DB55AC1A6829D801915981C46EDBFC64A | N |
| han | localhost | *7B3022FCAEC3534CE67C68322D8AF0C240D95745 | N |
+----------------+-----------+-------------------------------------------+------------------+
8 rows in set (0.00 sec)
Show Users that Have Access to a Particular Database
The information about the database-level privileges is stored in the mysql.db table.
You can query the table to find out which users have access to a given database and the level of the privileges.
For example, to get a list of all users that have some level access to the database named db_name you would use the following query:
SELECT * FROM mysql.db WHERE Db = 'db_name'\G;
*************************** 1. row ***************************
Host: localhost
Db: db_name
User: db_user
Select_priv: Y
Insert_priv: Y
Update_priv: Y
Delete_priv: Y
Create_priv: Y
Drop_priv: Y
Grant_priv: N
References_priv: Y
Index_priv: Y
Alter_priv: Y
Create_tmp_table_priv: Y
Lock_tables_priv: Y
Create_view_priv: Y
Show_view_priv: Y
Create_routine_priv: Y
Alter_routine_priv: Y
Execute_priv: Y
Event_priv: Y
Trigger_priv: Y
1 row in set (0.00 sec)
To fetch information only about the user accounts that have access to a given database, without displaying the privileges use:
SELECT db, host, user FROM mysql.db WHERE db = 'db_name'
+---------+-----------+---------+
| db | host | user |
+---------+-----------+---------+
| db_name | localhost | db_user |
+---------+-----------+---------+
The following query will show you information about all databases and associated users:
SELECT db, host, user FROM mysql.db;
+------------------+-----------+-----------+
| db | host | user |
+------------------+-----------+-----------+
| db_name | localhost | db_user |
| ghost_production | localhost | chewbacca |
| blog_db | localhost | leia |
| linuxize | localhost | han |
+------------------+-----------+-----------+
Conclusion
In this tutorial, we have shown how to get a list of all MySQL users and find out which users have access to a particular database.
6. How to Back Up and Restore MySQL Databases with Mysqldump
This tutorial explains how to backup and restore MySQL or MariaDB databases from the command line using the mysqldump utility.
The backup files created by the mysqldump utility are basically a set of SQL statements that can be used to recreate the original database. The mysqldump command can also generate files in CSV and XML format.
You can also use the mysqldump utility to transfer your MySQL database to another MySQL server.
If you don’t backup your databases, a software bug or a hard-drive failure could be disastrous. To help save you lots of time and frustration, it is strongly recommended that you take the precaution of regularly backing up your MySQL databases.
Mysqldump Command Syntax
Before going into how to use the mysqldump command, let’s start by reviewing the basic syntax.
The mysqldump utility expressions take the following form:
mysqldump [options] > file.sql
- options - The mysqldump options
- file.sql - The dump (backup) file
To use the mysqldump command the MySQL server must be accessible and running.
Backup a Single MySQL Database
The most common use case of the mysqldump tool is to backup a single database.
For example, to create a backup of the database named database_name using the user root and save it to a file named database_name.sql you would run the following command:
mysqldump -u root -p database_name > database_name.sql
You will be prompted to enter the root password. After successful authentication, the dump process will start. Depending on the database size, the process can take some time.
If you are logged in as the same user that you are using to perform the export and that the user does not require a password, you can omit the -u and -p options:
mysqldump database_name > database_name.sql
Backup Multiple MySQL Databases
To backup multiple MySQL databases with one command you need to use the --database option followed by the list of databases you want to backup. Each database name must be separated by space.
mysqldump -u root -p --databases database_name_a database_name_b > databases_a_b.sql
The command above will create a dump file containing both databases.
Backup All MySQL Databases
Use the --all-databases option to back up all the MySQL databases:
mysqldump -u root -p --all-databases > all_databases.sql
Same as with the previous example the command above will create a single dump file containing all the databases.
Backup all MySQL databases to separate files
The mysqldump utility doesn’t provide an option to backup all databases to separate files but we easily achieve that with a simple bash FOR loop :
for DB in $(mysql -e 'show databases' -s --skip-column-names); do
mysqldump $DB > "$DB.sql";
done
The command above will create a separate dump file for each database using the database name as the filename.
Create a Compressed MySQL Database Backup
If the database size is very large it is a good idea to compress the output. To do that simply pipe the output to the gzip utility, and redirect it to a file as shown below:
mysqldump database_name | gzip > database_name.sql.gz
Create a Backup with Timestamp
If you want to keep more than one backup in the same location, then you can add the current date to the backup filename:
mysqldump database_name > database_name-$(date +%Y%m%d).sql
The command above will create a file with the following format database_name-20180617.sql
Restoring a MySQL dump
You can restore a MySQL dump using the mysql tool. The command general syntax is as follows:
mysql database_name < file.sql
In most cases you’ll need to create a database to import into. If the database already exists, first you need to delete it.
In the following example the first command will create a database named database_name and then it will import the dump database_name.sql into it:
mysql -u root -p -e "create database database_name";mysql -u root -p database_name < database_name.sql
Restore a Single MySQL Database from a Full MySQL Dump
If you backed up all your databases using the -all-databases option and you want to restore a single database from a backup file which contains multiple databases use the --one-database option as shown below:
mysql --one-database database_name < all_databases.sql
Export and Import a MySQL Database in One Command
Instead of creating a dump file from one database and then import the backup into another MySQL database you can use the following one-liner:
mysqldump -u root -p database_name | mysql -h remote_host -u root -p remote_database_name
The command above will pipe the output to a mysql client on the remote host and it will import it into a database named remote_database_name. Before running the command, make sure the database already exists on the remote server.
Automate Backups with Cron
Automating the process of backing up the databases is as simple as creating a cron job what will run the mysqldump command at specified time.
To set up automated backups of a MySQL database using cronjob, follow the steps below:
Create a file named .my.cnf in your user home directory:
sudo nano ~/.my.cnf
Copy and paste the following text into the .my.cnf file.
[client]
user = dbuser
password = dbpasswd
- Do not forget to replace dbuser and dbpasswdwith the database user and user’s password.
- Restrict permissions of the credentials file so that only your user has access to it:
chmod 600 ~/.my.cnf
Create a directory to store the backups:
mkdir ~/db_backups
Open your user crontab file:
crontab -e
Add the following cron job that will create a backup of a database name mydb every day at 3am:
0 3 * * * /usr/bin/mysqldump -u dbuser mydb > /home/username/db_backups/mydb-$(date +\%Y\%m\%d).sql
- Do not forget to replace username with your actual user name. We’re also escaping the percent-signs (%), because they have special meaning in crontab.
You can also create another cronjob to delete any backups older than 30 days:
find /path/to/backups -type f -name "*.sql" -mtime +30 -delete
Conclusion
This tutorial covers only the basics, but it should be a good starting for anyone who wants to learn how to create and restore MySQL databases from the command line using the mysqldump utility.