MySQL Grant User: Database Access Tutorial

In MySQL, granting a user permission to access a specific database can be achieved through the following steps:

  1. Connect to the MySQL database server:
mysql -u root -p
  1. Create a new user (if the user doesn’t already exist):
CREATE USER 'new_user'@'localhost' IDENTIFIED BY 'password';
  1. Grant user permission to access a database.
GRANT ALL PRIVILEGES ON database_name.* TO 'new_user'@'localhost';

In the above command, ‘database_name’ is the name of the database to be granted access to, ‘new_user’ is the user to be granted access, ‘localhost’ is the hostname of the user, and ‘all’ represents granting access to all tables. You can also adjust the permission levels as needed, for example, GRANT SELECT, INSERT, UPDATE, DELETE ON database_name TO ‘new_user’@‘localhost’;

  1. Refresh permissions.
FLUSH PRIVILEGES;

By doing so, a user has been granted access to a certain database. You can verify if the user has the appropriate permissions by querying the user table in the mysql database.

SELECT * FROM mysql.user WHERE User = 'new_user' AND Host = 'localhost';

Please be cautious when granting permissions in a production environment to avoid security risks.

bannerAds