Data Control Language

 Data Control Language (DCL)



๐Ÿ”น Step 1: Login as Admin (root)

Open MySQL command line and login as root (or another admin account):

mysql -u root -p

Enter your root password.


๐Ÿ”น Step 2: Create Database and Table

CREATE DATABASE UniversityDB; USE UniversityDB; CREATE TABLE Students ( StudentID INT PRIMARY KEY, Name VARCHAR(50), Marks INT ); INSERT INTO Students VALUES (1, 'Amit', 85), (2, 'Raj', 70), (3, 'Neha', 92), (4, 'Sneha', 60);

๐Ÿ”น Step 3: Create Users

CREATE USER 'user1'@'localhost' IDENTIFIED BY 'pass1'; CREATE USER 'user2'@'localhost' IDENTIFIED BY 'pass2'; CREATE USER 'user3'@'localhost' IDENTIFIED BY 'pass3';


'localhost' means these users can log in only from the same computer where MySQL is running.
If you want them to connect from anywhere, use '%' instead of 'localhost'.


๐Ÿ”น Step 4: Grant Privileges

  • user1 → read-only

GRANT SELECT ON UniversityDB.Students TO 'user1'@'localhost';
  • user2 → insert-only

GRANT INSERT ON UniversityDB.Students TO 'user2'@'localhost';
  • user3 → full access

GRANT SELECT, INSERT, UPDATE, DELETE ON UniversityDB.Students TO 'user3'@'localhost';
  • If you want user3 to also be able to grant privileges to others:

GRANT SELECT ON UniversityDB.Students TO 'user3'@'localhost' WITH GRANT OPTION;

๐Ÿ”น Step 5: Apply Privileges

FLUSH PRIVILEGES;

๐Ÿ”น Step 6: Test Users

Exit root session:

EXIT;

Now log in as each user:

Login as user1:

mysql -u user1 -p

Password: pass1

Try:

USE UniversityDB; SELECT * FROM Students; -- Works INSERT INTO Students VALUES (5,'Kiran',77); -- Error

Login as user2:

mysql -u user2 -p

Password: pass2

Try:

USE UniversityDB; INSERT INTO Students VALUES (6,'Meena',88); -- Works SELECT * FROM Students; -- Error

Login as user3:

mysql -u user3 -p

Password: pass3

Try:

USE UniversityDB; UPDATE Students SET Marks=95 WHERE StudentID=2; -- Works DELETE FROM Students WHERE StudentID=1; -- Works (unless revoked)




๐Ÿ”น Step 7: Revoke Example

If you want to take away insert permission from user2:

REVOKE INSERT ON UniversityDB.Students FROM 'user2'@'localhost'; FLUSH PRIVILEGES;

Now user2 cannot insert anymore.






Comments

Popular posts from this blog

Checkpoint

SUB Queries