Your cart is currently empty!
Author: alien
-
Khóa học miễn phí MySQL – Show Privileges nhận dự án làm có lương
MySQL – Show Privileges
Table of content
The users in MySQL must have enough privileges to interact with the server. This is possible by assigning authentication details, like passwords to the users. In addition to this, operational or administrative privileges are granted separately if a user wants to interact with and operate on the data.
The MySQL SHOW Privileges
The MySQL SHOW PRIVILEGES Statement displays the list of privileges that are supported by the MYSQL server. The displayed list includes all static and currently registered dynamic privileges.
The information (returned list) contains three columns −
- Privilege − Name of the privilege
- Context − Name of the MySQL object for which the privilege is applicable.
- Comment − A string value describing the purpose of the privilege.
Syntax
Following is the syntax to list out all privileges in a MySQL Server −
SHOW PRIVILEGES;
Example
Following query lists out all the privileges supported by the MySQL server −
SHOW PRIVILEGES
Output
After executing the above code, we get the following output −
Privilege Context Comment Alter Tables To alter the table Alter routine Functions, Procedures To alter or drop stored functions/procedures Create Databases, Tables, Indexes To create new databases and tables Create routine Databases To use CREATE FUNCTION/PROCEDURE Create role Server Admin To create new roles Create temporary tables Databases To use CREATE TEMPORARY TABLE Create view Tables To create new views Create user Server Admin To create new users Delete Tables To delete existing rows Drop Databases, Tables To drop databases, tables, and views Drop role Server Admin To drop roles Event Server Admin To create, alter, drop and execute events Execute Functions, Procedures To execute stored routines File File access on server To read and write files on the server Grant option Databases, Tables, Funcs, Procedures To give to other users those privileges you possess Index Tables To create or drop indexes Insert Tables To insert data into tables Lock tables Databases To use LOCK TABLES (together with SELECT privilege) Process Server Admin To view the plain text of currently executing queries Proxy Server Admin To make proxy user possible References Databases,Tables To have references on tables Reload Server Admin To reload or refresh tables, logs and privileges Replication client Server Admin To ask where the slave or master servers are Replication slave Server Admin To read binary log events from the master Select Tables To retrieve rows from table Show databases Server Admin To see all databases with SHOW DATABASES Show view Tables To see views with SHOW CREATE VIEW Shutdown Server Admin To shut down the server Super Server Admin To use KILL thread, SET GLOBAL, CHANGE MASTER, etc. Trigger Tables To use triggers Create tablespace Server Admin To create/alter/drop tablespaces Update Tables To update existing rows Usage Server Admin No privileges – allow connect only 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 Listing Privileges Using a Client Program
Now, let us see how to retrieve/list all the privileges granted to the current MySQL user using a client program in programming languages like Java, PHP, Python, JavaScript, C++ etc.
Syntax
Following are the syntaxes −
To show all the privileges granted to an user, we need to pass the SHOW PRIVILEGES statement as a parameter to the query() function of the PHP mysqli library as −
$sql = "SHOW PRIVILEGES"; $mysqli->query($sql);
Following is the syntax to show all the privileges granted to the current user through a JavaScript program −
sql= "SHOW PRIVILEGES;" con.query(sql, function (err, result) { if (err) throw err; console.log(result); });
To show the privileges of the current user, we need to execute the SHOW PRIVILEGES statement using the JDBC executeQuery() function as −
String sql = "SHOW PRIVILEGES"; statement.executeQuery(sql);
Following is the syntax to show all the privileges granted to the current MySQL user through a Python program −
sql = f"SHOW GRANTS FOR ''{username_to_show}''@''localhost''"; cursorObj.execute(sql);
Example
Following are the programs −
$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();Output
The output obtained is as follows −
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); }); });
Output
The output produced is as follows −
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://localhost: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(); } } }
Output
The output obtained is as shown below −
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()
Output
Following is the output of the above code −
Privileges for user ''newUser'' are: GRANT USAGE ON *.* TO `newUser`@`localhost` GRANT SELECT, INSERT, UPDATE ON `your_database`.* TO `newUser`@`localhost`
Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc
Khóa học miễn phí MySQL – Grant Privileges nhận dự án làm có lương
MySQL – Grant Privileges
As we learnt earlier, a root user is connected to the server (using a password) immediately after installing MySQL. The privileges available to this user are default. The user accessing MySQL using root account has enough privileges to perform basic operations on the data. However, in exceptional cases, the user must manually request the host to grant privileges.
The MySQL Grant Privileges
MySQL provides several SQL statements to allow or restrict administrative privileges for users to interact with the data stored in the database. They are listed below −
-
GRANT statement
-
REVOKE statement
In this tutorial, let us learn about the GRANT statement in detail.
The MySQL GRANT Statement
The MySQL GRANT statement is used to assign various privileges or roles to MySQL user accounts. However, it”s important to note that you cannot assign both privileges and roles in a single GRANT statement. To grant privileges to users using this statement, you need to have the GRANT OPTION privilege.
Syntax
Following is the syntax of the MySQL GRANT Statement −
GRANT privilege1, privilege2, privilege3... ON object_type TO user_or_role1, user_or_role2, user_or_role3... [WITH GRANT OPTION] [AS user [WITH ROLE DEFAULT | NONE | ALL | ALL EXCEPT role [, role ] ... | role [, role ] ... ] ]
Example
Assume we have created a user named ”test_user”@”localhost” in MySQL using the CREATE USER statement −
CREATE USER ''test_user''@''localhost'' IDENTIFIED BY ''testpassword
Following is the output of the above code −
Query OK, 0 rows affected (0.23 sec)
Now, let us create a database −
CREATE DATABASE test_database;
The output produced is as follows −
Query OK, 0 rows affected (0.56 sec)
Next, we will use the created database −
USE test_database;
We get the output as shown below −
Database changed
Now, let us create a table in the database −
CREATE TABLE MyTable(data VARCHAR(255));
The output obtained is as follows −
Query OK, 0 rows affected (0.67 sec)
Following query grants SELECT privileges on the table created above to the user ”test_user”@”localhost” −
GRANT SELECT ON test_database.MyTable TO ''test_user''@''localhost
After executing the above code, we get the following output −
Query OK, 0 rows affected (0.31 sec)
Verification
You can verify the granted privileges using the SHOW GRANTS statements −
SHOW GRANTS FOR ''test_user''@''localhost
The output we get is as shown below −
Grants for test_user@localhost |
---|
GRANT USAGE ON *.* TO `test_user`@`localhost` |
GRANT SELECT ON `test_database`.`mytable` TO `test_user`@`localhost` |
Granting Various Privileges
We know that the MySQL GRANT statement allows a wide range of privileges to user accounts. Here is a list of some commonly used privileges that can be granted using the GRANT statement −
Privileges | Description |
---|---|
ALTER | Allows users to modify table structures using the ALTER TABLE statement. |
CREATE | Grants the ability to create new objects such as tables and databases. |
DELETE | Enables users to delete rows from tables. |
INSERT | Allows users to insert new records into tables. |
SELECT | Provides read access to tables, allowing users to retrieve data. |
UPDATE | Allows users to modify existing data in tables. |
SHOW DATABASES | Grants the ability to see a list of available databases. |
CREATE USER | Allows users to create new MySQL user accounts. |
GRANT OPTION | Provides users with the authority to grant privileges to other users. |
SUPER | Grants high-level administrative privileges. |
SHUTDOWN | Allows users to shut down the MySQL server. |
REPLICATION CLIENT | Provides access to replication-related information. |
REPLICATION SLAVE | Enables users to act as a replication slave server. |
FILE | Grants permission to read and write files on the server”s file system. |
CREATE VIEW | Allows users to create new database views. |
CREATE TEMPORARY TABLES | Allows the creation of temporary tables. |
EXECUTE | Enables users to execute stored procedures and functions. |
TRIGGER | Provides the ability to create and manage triggers. |
EVENT | Grants the ability to create and manage events. |
SHOW VIEW | Allows users to see the definition of views. |
INDEX | Enables users to create and drop indexes on tables. |
PROXY | Provides the capability to proxy or impersonate other users. |
To GRANT all the available privileges to a user, you need to use the ”ALL” keyword in the GRANT statement −
GRANT ALL ON test_database.MyTable TO ''test_user''@''localhostOutput
After executing the above code, we get the following output −
Query OK, 0 rows affected (0.13 sec)
Granting Privileges on Stored Routines
To grant privileges on stored routines, such as tables, procedures or functions, in MySQL, you need to specify the object type (PROCEDURE or FUNCTION) after the ON clause followed by the name of the routine.
You can grant ALTER ROUTINE, CREATE ROUTINE, EXECUTE, and GRANT OPTION privileges on these stored routines.
Example
Assume we have created a stored procedure and a stored function with the name ”sample” in the current database as follows −
//Creating a procedure DELIMITER // CREATE PROCEDURE sample () BEGIN SELECT ''This is a sample procedure END// Query OK, 0 rows affected (0.29 sec) //Creating a function CREATE FUNCTION sample() RETURNS VARCHAR(120) DETERMINISTIC BEGIN DECLARE val VARCHAR(120); SET val = ''This is a sample function return val; END// DELIMITER ;
Following is the output obtained −
Query OK, 0 rows affected (0.34 sec)
After creating these stored routines, you can grant ALTER ROUTINE, EXECUTE privileges on the above created procedure to the user named ”test_user”@”localhost” as follows −
GRANT ALTER ROUTINE, EXECUTE ON PROCEDURE test_database.sample TO ''test_user''@''localhost
The output produced is as shown below −
Query OK, 0 rows affected (0.24 sec)
Now, the query below grants ALTER ROUTINE, EXECUTE privileges on the above created function to the user named ”test_user”@”localhost”.
GRANT ALTER ROUTINE, EXECUTE ON FUNCTION test_database.sample TO ''test_user''@''localhost
Following is the output of the above query −
Query OK, 0 rows affected (0.15 sec)
Privileges to Multiple Users
You can grant privileges to multiple users. To do so, you need to provide the names of the objects or users separated by commas.
Example
Assume we have created a table named ”sample” and three user accounts using the CREATE statement as shown below.
Creating a table −
CREATE TABLE sample (data VARCHAR(255));
We will get the output as shown below −
Query OK, 0 rows affected (3.55 sec)
Now, let us create the user accounts.
Creating User ”test_user1” −
CREATE USER test_user1 IDENTIFIED BY ''testpassword
The output obtained is as follows −
Query OK, 0 rows affected (0.77 sec)
Creating User ”test_user2” −
CREATE USER test_user2 IDENTIFIED BY ''testpassword
Following is the output produced −
Query OK, 0 rows affected (0.28 sec)
Creating the 3rd user −
Creating User ”test_user3” −
CREATE USER test_user3 IDENTIFIED BY ''testpassword
We get the output as follows −
Query OK, 0 rows affected (0.82 sec)
Following query grant SELECT, INSERT and UPDATE privileges on the tables ”sample1”, ”sample2” and ”sample3” to to all three users (”test_user1”, ”test_user2”, and ”test_user3”) using a single GRANT statement.
GRANT SELECT, INSERT, UPDATE ON TABLE sample TO test_user1, test_user2, test_user3;
Output
After executing the above code, we get the following output −
Query OK, 0 rows affected (0.82 sec)
Global Privileges
Instead of specifying the table, procedure or a function you can grant global privileges: privileges that apply to all databases to a user. To do so, you need to use *.* after the ON clause.
Example
Following query grants SELECT, INSERT and UPDATE privileges on all databases to the user named ”test_user”@”localhost” −
GRANT SELECT, INSERT, UPDATE ON *.* TO ''test_user''@''localhost
Output
Following is the output obtained −
Query OK, 0 rows affected (0.43 sec)
Example
Similarly, following query grants all privileges on all the databases to the ”test_user”@”localhost −
GRANT ALL ON *.* TO ''test_user''@''localhost
Output
The output produced is as shown below −
Query OK, 0 rows affected (0.41 sec)
Database Level Privileges
You can grant privileges to all the objects in a database by specifying the database name followed by “.*” after the ON clause.
Example
Following query grants SELECT, INSERT and UPDATE privileges on all objects in the database named test to the user ”test_user”@”localhost” −
GRANT SELECT, INSERT, UPDATE ON test.* TO ''test_user''@''localhost
Output
Following is the output of the above code −
Query OK, 0 rows affected (0.34 sec)
Example
Similarly, following query grants all privileges on all the databases to the ”test_user”@”localhost −
GRANT ALL ON test.* TO ''test_user''@''localhost
Output
Output of the above code is as follows −
Query OK, 0 rows affected (0.54 sec)
Column Level Privileges
You can grant privileges on a specific column of a table to a user. To do so, you need to specify the column names after the privileges.
Example
Assume we have created a table named Employee using the CREATE query as −
CREATE TABLE Employee ( ID INT, Name VARCHAR(15), Phone INT, SAL INT);
The output produced is as shown below −
Query OK, 0 rows affected (6.47 sec)
Following query grants SELECT privilege to the user named ”test_user”@”localhost” on the ID column and INSERT and UPDATE privileges on the columns Name and Phone of the Employee table −
GRANT SELECT (ID), INSERT (Name, Phone) ON Employee TO ''test_user''@''localhost
The output obtained is as follows −
Query OK, 0 rows affected (0.54 sec)
Proxy User Privileges
You can make one user as a proxy of another by granting the PROXY privilege to it. If you do so, both users have the same privileges.
Example
Assume we have created a users named sample_user, proxy_user in MySQL using the CREATE statement as shown below −
CREATE USER sample_user, proxy_user IDENTIFIED BY ''testpassword
Following is the output obtained −
Query OK, 0 rows affected (0.52 sec)
The following query grants SELECT and INSERT privileges on the Employee table created above to the user sample_user −
GRANT SELECT, INSERT ON Emp TO sample_user;
We get the output as shown below −
Query OK, 0 rows affected (0.28 sec)
Now, we can assign proxy privileges to the user proxy_user using the GRANT statement as shown below −
GRANT PROXY ON sample_user TO proxy_user;
The output is as follows −
Query OK, 0 rows affected (1.61 sec)
Granting Roles
Role in MySQL is a set of privileges with name. You can create one or more roles in MySQL using the CREATE ROLE statement. If you use the GRANT statement without the ON clause, you can grant a role instead of privileges.
Example
Let us start by creating a role named TestRole_ReadOnly.
CREATE ROLE ''TestRole_ReadOnly
Following is the output obtained −
Query OK, 0 rows affected (0.13 sec)
Now, let us grant read only privilege to the created role using the GRANT statement for accessing all objects within the database −
GRANT SELECT ON * . * TO ''TestRole_ReadOnly
The output of this GRANT statement should be −
Query OK, 0 rows affected (0.14 sec)
Then, you can GRANT the created role to a specific user. First, you will need to create the user as shown below −
CREATE USER ''newuser''@''localhost'' IDENTIFIED BY ''password
Following is the output produced −
Query OK, 0 rows affected (0.14 sec)
Now, you can grant the ”TestRole_ReadOnly” role to ”newuser”@”localhost” −
GRANT ''TestRole_ReadOnly'' TO ''newuser''@''localhost
The output obtained is as shown below −
Query OK, 0 rows affected (0.13 sec)
Granting Privileges Using a Client Program
Now, let us see how to grant privileges to a MySQL user using the client program.
Syntax
Following are the syntaxes −
To grant all the privileges to an user in MySQL database using the PHP program, we need to execute the GRANT ALL statement as shown below −
$sql = "GRANT ALL PRIVILEGES ON database_name.* TO ''username''@''localhost''"; $mysqli->query($sql);
Following is the syntax to grant a particular privilege to the desired user using a JavaScript program −
sql= "GRANT privilege_name(s) ON object TO user_account_name"; con.query(sql, function (err, result) { if (err) throw err; console.log(result); });
To grant the privilege in MySQL database, we need to execute the GRANT ALL PRIVILEGES statement using the JDBC execute() function as −
String sql = "GRANT ALL PRIVILEGES ON DATABASE_NAME.* TO ''USER_NAME''@''localhost''"; statement.execute(sql);
Following is the syntax to grant a particular privilege to the desired user using a Python program −
sql = f"GRANT {privileges} ON your_database.* TO ''{username_to_grant}''@''localhost''"; cursorObj.execute(sql);
Example
Following are the programs −
$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 = "GRANT ALL PRIVILEGES ON tutorials.* TO ''Revathi''@''localhost''"; if($result = $mysqli->query($sql)){ printf("Grant privileges executed successfully...!"); } if($mysqli->error){ printf("Failed..!" , $mysqli->error); } $mysqli->close();
Output
The output obtained is as follows −
Grant privileges executed successfully...!
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 = "CREATE USER ''test_user''@''localhost'' IDENTIFIED BY ''testpassword" con.query(sql); sql = "CREATE DATABASE test_database;" con.query(sql); sql = "USE test_database;" con.query(sql); sql = "CREATE TABLE MyTable(data VARCHAR(255));" con.query(sql); sql = "GRANT SELECT ON test_database.MyTable TO ''test_user''@''localhost" con.query(sql); sql = "SHOW GRANTS FOR ''test_user''@''localhost"; con.query(sql, function(err, result){ if (err) throw err; console.log(result); }); });
Output
The output produced is as follows −
Connected! -------------------------- [ { ''Grants for test_user@localhost'': ''GRANT USAGE ON *.* TO `test_user`@`localhost`'' }, { ''Grants for test_user@localhost'': ''GRANT SELECT ON `test_database`.`mytable` TO `test_user`@`localhost`'' } ]
import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class GranPriv { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/TUTORIALS"; String user = "root"; String password = "password"; 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 = "GRANT ALL PRIVILEGES ON tutorials.* TO ''Vivek''@''localhost''"; st.execute(sql); System.out.println("You grant all privileges to user ''Vivek''...!"); }catch(Exception e) { e.printStackTrace(); } } }
Output
The output obtained is as shown below −
You grant all privileges to user ''Vivek''...!
import mysql.connector # creating the connection object connection = mysql.connector.connect( host=''localhost'', user=''root'', password=''password'' ) username_to_grant = ''newUser'' # privileges we want to grant privileges = ''SELECT, INSERT, UPDATE'' # Create a cursor object for the connection cursorObj = connection.cursor() cursorObj.execute(f"GRANT {privileges} ON your_database.* TO ''{username_to_grant}''@''localhost''") print(f"Privileges granted to user ''{username_to_grant}'' successfully.") cursorObj.close() connection.close()
Output
Following is the output of the above code −
Privileges granted to user ''newUser'' successfully.
Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc