Today we will talk about the most common activities performed when administering a MySQL server.
The first thing we need to know is how to log in to MySQL, this can be accomplished by using the following command:
$ mysql -h host_name_or_IP -P port_number -u user_name -p
Where: -h allows you to specify witch FQDN or IP address MySQL client must connect to (localhost by default), -P port number where MySQL is listening (3306 default), -u means username (root by default), and -p means prompt for password.
Note: if we want to connect with the root account to localhost on port 3306 you just need to type:
$ mysql -p
Create users
There are three methods for creating users in MySQL, one is by using CREATE command, other is by manually modifying the user table of the MySQL database, the last one consist in creating users via GRANT commands.
The first method is recommended by the MySQL developers because is less prone to human errors (depending of the human ;)). The syntax of the command is the following:
mysql> CREATE USER 'user_name'@'host_name_or_IP'\
IDENTIFIED BY my_password';
With the last commands MySQL created a user called user_name that has permission to log to a MySQL server with the address host_name_or_IP and has the password my_password. For example if we want to create a user named aang, that has permission to log in localhost and has the password appa you have to use the following command:
mysql> CREATE USER 'aang'@'localhost' IDENTIFIED BY 'appa';
If we want to create a user with the second method, we do the following:
mysql> INSERT INTO mysql.user VALUES ('host_name_or_IP',\
'user_name', PASSWORD('my_password'), 'Y', 'Y', 'Y', 'Y',\
'Y','Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y',\
'Y', 'Y','Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', '', '', '',\
'', 0, 0, 0, 0);
So the user aang that logs in localhost and has appa for password will be created with this:
mysql> INSERT INTO mysql.user VALUES ('localhost', 'aang',\
PASSWORD('appa'), 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y',\
'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y',\
'Y', 'Y', 'Y', 'Y', 'Y', 'Y', '', '', '', '', 0, 0, 0, 0);
With GRANT we will accomplish the same if we do the following:
GRANT ALL ON database_name.* TO 'user_name'@'host_name_or_IP' IDENTIFIED BY 'my_password';
Delete users
We have two methods for deleting users: DROP USER and DELETE FROM mysql.user.
First method:
mysql> DROP USER 'aang'@'localhost';
Second method:
mysql> DELETE FROM mysql.user WHERE User='aang';