MySQL - 显示权限



MySQL 中的用户必须拥有足够的权限才能与服务器交互。这可以通过为用户分配身份验证详细信息(如密码)来实现。此外,如果用户希望与数据交互并在数据上进行操作,则会分别授予操作或管理权限。

MySQL SHOW PRIVILEGES

MySQL SHOW PRIVILEGES 语句显示 MYSQL 服务器支持的权限列表。显示的列表包括所有静态和当前注册的动态权限。

信息(返回列表)包含三列 -

  • 权限 - 权限的名称
  • 上下文 - 权限适用的 MySQL 对象的名称。
  • 注释 - 描述权限用途的字符串值。

语法

以下是列出 MySQL 服务器中所有权限的语法 -

SHOW PRIVILEGES;

示例

以下查询列出 MySQL 服务器支持的所有权限 -

SHOW PRIVILEGES

输出

执行上述代码后,我们将获得以下输出 -

权限 上下文 注释
Alter Tables 更改表
Alter routine Functions, Procedures 更改或删除存储函数/过程
Create Databases, Tables, Indexes 创建新的数据库和表
Create routine Databases 使用 CREATE FUNCTION/PROCEDURE
Create role Server Admin 创建新角色
Create temporary tables Databases 使用 CREATE TEMPORARY TABLE
Create view Tables 创建新视图
Create user Server Admin 创建新用户
Delete Tables 删除现有行
Drop Databases, Tables 删除数据库、表和视图
Drop role Server Admin 删除角色
Event Server Admin 创建、更改、删除和执行事件
Execute Functions, Procedures 执行存储例程
File 服务器上的文件访问 在服务器上读取和写入文件
Grant option Databases, Tables, Funcs, Procedures 将您拥有的这些权限授予其他用户
Index Tables 创建或删除索引
Insert Tables 将数据插入表中
Lock tables Databases 使用 LOCK TABLES(与 SELECT 权限一起使用)
Process Server Admin 查看当前正在执行的查询的纯文本
Proxy Server Admin 使代理用户成为可能
References Databases,Tables 对表进行引用
Reload Server Admin 重新加载或刷新表、日志和权限
Replication client Server Admin 询问从属服务器或主服务器在哪里
Replication slave Server Admin 从主服务器读取二进制日志事件
Select Tables 从表中检索行
Show databases Server Admin 使用 SHOW DATABASES 查看所有数据库
Show view Tables 使用 SHOW CREATE VIEW 查看视图
Shutdown Server Admin 关闭服务器
Super Server Admin 使用 KILL thread、SET GLOBAL、CHANGE MASTER 等。
Trigger Tables 使用触发器
Create tablespace Server Admin 创建/更改/删除表空间
Update Tables 更新现有行
用法 Server Admin 无权限 - 仅允许连接
BINLOG_ENCRYPTION_ADMIN Server Admin
AUDIT_ADMIN Server Admin
ENCRYPTION_KEY_ADMIN Server Admin
INNODB_REDO_LOG_ARCHIVE Server Admin
APPLICATION_PASSWORD_ADMIN Server Admin
SHOW_ROUTINE Server Admin
BACKUP_ADMIN Server Admin
BINLOG_ADMIN Server Admin
CLONE_ADMIN Server Admin
CONNECTION_ADMIN Server Admin
SET_USER_ID Server Admin
SERVICE_CONNECTION_ADMIN Server Admin
GROUP_REPLICATION_ADMIN Server Admin
REPLICATION_APPLIER Server Admin
INNODB_REDO_LOG_ENABLE Server Admin
PERSIST_RO_VARIABLES_ADMIN Server Admin
TABLE_ENCRYPTION_ADMIN Server Admin
ROLE_ADMIN Server Admin
REPLICATION_SLAVE_ADMIN Server Admin
SESSION_VARIABLES_ADMIN Server Admin
RESOURCE_GROUP_ADMIN Server Admin
RESOURCE_GROUP_USER Server Admin
SYSTEM_USER Server Admin
SYSTEM_VARIABLES_ADMIN Server Admin
XA_RECOVER_ADMIN Server Admin

使用客户端程序列出权限

现在,让我们看看如何在编程语言(如 Java、PHP、Python、JavaScript、C++ 等)中使用客户端程序检索/列出授予当前 MySQL 用户的所有权限。

语法

以下是语法 -

要显示授予用户的全部权限,我们需要将 **SHOW PRIVILEGES** 语句作为参数传递给 PHP mysqli 库的 **query()** 函数,如下所示 -

$sql = "SHOW PRIVILEGES";
$mysqli->query($sql);

以下是通过 JavaScript 程序显示授予当前用户的所有权限的语法 -

sql= "SHOW PRIVILEGES;"
con.query(sql, function (err, result) {
   if (err) throw err;
      console.log(result);
});

要显示当前用户的权限,我们需要使用 JDBC 的 executeQuery() 函数执行 SHOW PRIVILEGES 语句,如下所示:

String sql = "SHOW PRIVILEGES";
statement.executeQuery(sql);

以下是通过 Python 程序显示授予当前 MySQL 用户的所有权限的语法:

sql = f"SHOW GRANTS FOR '{username_to_show}'@'localhost'";
cursorObj.execute(sql);

示例

以下是程序:

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$mysqli = new mysqli($dbhost, $dbuser, $dbpass);
if($mysqli->connect_errno ) {
   printf("Connect failed: %s
", $mysqli->connect_error); exit(); } //printf('Connected successfully.
'); $sql = "SHOW PRIVILEGES"; if($result = $mysqli->query($sql)){ printf("PRIVILEGES found successfully...!"); printf("Lists are: "); while($row = mysqli_fetch_array($result)){ print_r($row); } } if($mysqli->error){ printf("Failed..!" , $mysqli->error); } $mysqli->close();

输出

获得的输出如下:

PRIVILEGES found successfully...!Lists are: Array
(
    [0] => Alter
    [Privilege] => Alter
    [1] => Tables
    [Context] => Tables
    [2] => To alter the table
    [Comment] => To alter the table
)
Array
(
    [0] => Alter routine
    [Privilege] => Alter routine
    [1] => Functions,Procedures
    [Context] => Functions,Procedures
    [2] => To alter or drop stored functions/procedures
    [Comment] => To alter or drop stored functions/procedures
)
Array
(
    [0] => Create
    [Privilege] => Create
    [1] => Databases,Tables,Indexes
    [Context] => Databases,Tables,Indexes
    [2] => To create new databases and tables
    [Comment] => To create new databases and tables
)
Array
(
    [0] => Create routine
    [Privilege] => Create routine
    [1] => Databases
    [Context] => Databases
    [2] => To use CREATE FUNCTION/PROCEDURE
    [Comment] => To use CREATE FUNCTION/PROCEDURE
)
Array
(
    [0] => Create role
    [Privilege] => Create role
    [1] => Server Admin
    [Context] => Server Admin
    [2] => To create new roles
    [Comment] => To create new roles
)
..........

 (
    [0] => REPLICATION_SLAVE_ADMIN
    [Privilege] => REPLICATION_SLAVE_ADMIN
    [1] => Server Admin
    [Context] => Server Admin
    [2] =>
    [Comment] =>
)
Array
(
    [0] => SENSITIVE_VARIABLES_OBSERVER
    [Privilege] => SENSITIVE_VARIABLES_OBSERVER
    [1] => Server Admin
    [Context] => Server Admin
    [2] =>
    [Comment] =>
)
var mysql = require('mysql2');
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "Nr5a0204@123"
});

  //Connecting to MySQL
  con.connect(function (err) {
  if (err) throw err;
  console.log("Connected!");
  console.log("--------------------------");

  sql = "SHOW PRIVILEGES";
  con.query(sql, function(err, result){
    if (err) throw err;
    console.log(result);
  });
});

输出

产生的输出如下:

Connected!
--------------------------
[
  {
    Privilege: 'Alter',
    Context: 'Tables',
    Comment: 'To alter the table'
  },
.
.
.
  {
    Privilege: 'TELEMETRY_LOG_ADMIN',
    Context: 'Server Admin',
    Comment: ''
  }
]
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ShowPriv {
	public static void main(String[] args) {
		String url = "jdbc:mysql://127.0.0.1:3306/TUTORIALS";
		String user = "root";
		String password = "password";
		ResultSet rs;
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
            Connection con = DriverManager.getConnection(url, user, password);
            Statement st = con.createStatement();
            //System.out.println("Database connected successfully...!");
            String sql = "SHOW PRIVILEGES";
            rs = st.executeQuery(sql);
            System.out.println("All privileges: "); 
            while(rs.next()) {
            	String priv = rs.getNString(1);
            	System.out.println(priv);
            }
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
}

输出

获得的输出如下所示:

All privileges: 
Alter
Alter routine
Create
Create routine
Create role
Create temporary tables
Create view
Create user
Delete
Drop
Drop role
Event
Execute
File
Grant option
Index
Insert
Lock tables
Process
Proxy
References
Reload
Replication client
Replication slave
Select
Show databases
Show view
Shutdown
Super
import mysql.connector
# creating the connection object
connection = mysql.connector.connect(
    host='localhost',
    user='root',
    password='password'
)
username_to_show = 'newUser'
# Create a cursor object for the connection
cursorObj = connection.cursor()
cursorObj.execute(f"SHOW GRANTS FOR '{username_to_show}'@'localhost'")
privileges = cursorObj.fetchall()
print(f"Privileges for user '{username_to_show}' are:")
for grant in privileges:
    print(grant[0])
cursorObj.close()
connection.close()

输出

以下是上述代码的输出:

Privileges for user 'newUser' are:
GRANT USAGE ON *.* TO `newUser`@`localhost`
GRANT SELECT, INSERT, UPDATE ON `your_database`.* TO `newUser`@`localhost`
广告