MySQL: Creating Users & Granting Access Simplified

By Angsuman Chakraborty, Gaea News Network
Friday, November 23, 2007

In MySQL you can use the GRANT statement to create users and assign privileges to them at the same time. It is extremely convenient and beats create user or directly hacking the mysql.user table. I learned few things about GRANT the hard way.

MySQL allows you to create users associated with a particular host name or a set of host names. This allows you to easily restrict your user account to a particular host or a small set of allowed hosts.
A mysql user is identified not only by the user name but also by the host name. So, for example, you can have separate privileges for user foo connecting from host bar and for user foo connecting from localhost.

It is a good policy to allow the least amount of security as you can do with. It is better to add privileges as needed as opposed to providing blanket privileges upfront.

A typical GRANT statement to GRANT all privileges to all tables on database db to user tim with password pass connecting from machine jaguar can be written as follows:
grant all on db.* to 'tim‘@’jaguar‘ identified by ‘pass‘;

To allows tim to connect only from localhost (same machine as the database) change it as follows:
grant all on db.* to 'tim‘@’localhost‘ identified by ‘pass‘;

To allows tim to connect only from any machine change it as follows:
grant all on db.* to 'tim‘@’%‘ identified by ‘pass‘;

To restrict tim connecting from localhost to only select & insert privilege in db database use:
grant select, insert on db.* to 'tim‘@’localhost‘ identified by ‘pass‘;

Reference: MySQL Manual

The full syntax for GRANT is:

GRANT priv_type [(column_list)] [, priv_type [(column_list)]] …
ON [object_type] {tbl_name | * | *.* | db_name.*}
TO user [IDENTIFIED BY [PASSWORD] ‘password’]
[, user [IDENTIFIED BY [PASSWORD] ‘password’]] …
[REQUIRE
NONE |
[{SSL| X509}]
[CIPHER 'cipher' [AND]]
[ISSUER 'issuer' [AND]]
[SUBJECT 'subject']]
[WITH with_option [with_option] …]

object_type =
TABLE
| FUNCTION
| PROCEDURE

with_option =
GRANT OPTION
| MAX_QUERIES_PER_HOUR count
| MAX_UPDATES_PER_HOUR count
| MAX_CONNECTIONS_PER_HOUR count
| MAX_USER_CONNECTIONS count

YOUR VIEW POINT
NAME : (REQUIRED)
MAIL : (REQUIRED)
will not be displayed
WEBSITE : (OPTIONAL)
YOUR
COMMENT :