I had this challenge when working on MySQL Ver 8.0.21
I wanted to grant permissions of a database named my_app_db
to the root
user running on localhost
host.
But when I run the command:
use my_app_db;
GRANT ALL PRIVILEGES ON my_app_db.* TO 'root'@'localhost';
I get the error:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'my_app_db.* TO 'root'@'localhost'' at line 1>
Here's how I fixed:
Login to your MySQL console. You can change root
to the user you want to login with:
mysql -u root -p
Enter your mysql root password
Next, list out all the users and their host on the MySQL server. Unlike PostgreSQL this is often stored in the mysql
database. So we need to select the mysql
database first:
use mysql;
SELECT user, host FROM user;
Note: if you don't run the use mysql
, you get the no database selected
error.
This should give you an output of this sort:
+------------------+-----------+
| user | host |
+------------------+-----------+
| mysql.infoschema | localhost |
| mysql.session | localhost |
| mysql.sys | localhost |
| root | localhost |
+------------------+-----------+
4 rows in set (0.00 sec)
Next, based on the information gotten from the list, grant privileges to the user that you want. We will need to first select the database before granting permission to it. For me, I am using the root
user that runs on the localhost
host:
use my_app_db;
GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';
Note: The GRANT ALL PRIVILEGES ON database_name.* TO 'root'@'localhost';
command may not work for modern versions of MySQL. Most modern versions of MyQL replace the database_name
with *
in the grant privileges command after you select the database that you want to use.
You can then exit the MySQL console:
exit
That's it.
I hope this helps
FLUSH PRIVILEGES
? – Romainflush privileges
is not needed when you usegrant
commands. x4 – PacerierFLUSH PRIVILEGES;
only if you modify the grant tables directly using statements such asINSERT
,UPDATE
, orDELETE
– simhumileco