MySQL的用户管理

    技术2025-10-08  6

    1. 创建新用户

    登录以root登录MySQL之后,执行下面两条指令:

    create user 'username'@'host' identified by 'password'; # host: % 表示任何ip都可以登录,localhost 表示仅可以本地登录,还可以指定ip,暂时没有尝试过指定域名 flush privileges; # 刷新权限,也没有尝试过不刷新权限直接登录

    Example:

    xiaoyao@Ubuntu2004:~$ mysql -uroot -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 11 Server version: 8.0.20-0ubuntu0.20.04.1 (Ubuntu) Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql> create user 'yaowenzhou'@'%' identified by '123456'; Query OK, 0 rows affected (0.00 sec) mysql> flush privileges; Query OK, 0 rows affected (0.01 sec) mysql>

    2. 修改密码

    如下指令:

    alter user 'username'@'host' identified by 'new password'; flush privileges;

    Example:

    mysql> alter user 'root'@'localhost' identified by '123456'; Query OK, 0 rows affected (0.01 sec) mysql> flush privileges; Query OK, 0 rows affected (0.01 sec) mysql>

    3. 授权

    grant all privileges on *.* to 'username'@'host' with grant option; # with grant option表示该用户可给其它用户赋予权限,但不可能超过该用户已有的权限 # 比如a用户有select,insert权限,也可给其它用户赋权 # 但它不可能给其它用户赋delete权限,除了select,insert以外的都不能 # 这句话可加可不加,视情况而定。 # all privileges 可换成select,update,insert,delete,drop,create等操作 # 如:grant select,insert,update,delete on *.* to 'test'@'localhost'; # 第一个*表示通配数据库,可指定新建用户只可操作的数据库 # 如:grant all privileges on 数据库.* to 'test'@'localhost'; # 第二个*表示通配表,可指定新建用户只可操作的数据库下的某个表 # 如:grant all privileges on 数据库.指定表名 to 'test'@'localhost';

    4. 查看用户授权信息

    show grants for 'username'@'host';

    5. 撤销权限

    revoke all privileges on *.* from 'username'@'host'; # 用户有什么权限就撤什么权限

    6. 删除用户

    drop user 'test'@'host';

    7. 修改某个用户可远程登录

    update user set host='%' where user ='root'; flush privileges;

    8. 修改某个用户的加密方式:

    ALTER USER "user_name"@"host" IDENTIFIED WITH mysql_native_password; # mysql_native_password/caching_sha2_password
    Processed: 0.017, SQL: 9