How to Create and Grant the MySQL Database User Print

  • 15

How to Create and Grant Database USER in MySQL:

STEP 1: We need to login to the MySQL prompt using below command because all operation will be executed in MySQL prompt.

[root@localhost ~]# mysql -u root -p

and need to login with MySQL root password.

STEP 2: CREATE NEW USER

We can create new MySQL user with the following command:

mysql> CREATE USER 'user'@'localhost' IDENTIFIED BY 'password'

where:

user – the name of the MySQL user which will be created
password – the password which we want to assign to that user

All MySQL commands are ends with a semicolon (;).

STEP 3: GRANT PERMISSIONS FOR A USER

The next thing that we will have to do is to grant privileges for that user in order to be able to access the MySQL and work with databases.
we grant all privileges to the MySQL user to all database tables related to the database with name "database".

mysql> GRANT ALL PRIVILEGES ON database.table TO 'user'@'localhost';

where:

database – the name of the MySQL database to which we grant access
table – the name of the database table to which we grant access

We are allowed to use the asterisk wildcard symbol (*) when we want to grant access to all databases/tables:

mysql> GRANT ALL PRIVILEGES ON database.* TO ‘user’@’localhost’;

or

mysql> GRANT ALL PRIVILEGES ON *.* TO ‘user’@’localhost’;

Here is a sample syntax where only two privileges are granted for the user:

mysql> GRANT SELECT, INSERT, DELETE ON database.* TO 'user'@'localhost';

Here is a list of the MySQL privileges which are most commonly used:

  • ALL PRIVILEGES – grants all privileges to the MySQL user
  • CREATE – allows the user to create databases and tables
  • DROP - allows the user to drop databases and tables
  • DELETE - allows the user to delete rows from specific MySQL table
  • INSERT - allows the user to insert rows into specific MySQL table
  • SELECT – allows the user to read the database
  • UPDATE - allows the user to update table rows

In order for the changes to take effect and the privileges to be saved the following command should be executed at the end:

mysql> FLUSH PRIVILEGES;

STEP 4: Remove an existing MySQL user

A MySQL user can be deleted with the following command:

mysql> DROP USER ‘user’@’localhost’;

Thats it!!


Was this answer helpful?

« Back