Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

DBMS CODES_PLSQL

The document provides a comprehensive overview of SQL concepts including DDL, DML, DQL, DCL, and various database functionalities like inbuilt functions, aggregate functions, constraints, joins, views, stored procedures, and triggers. It includes practical examples and SQL commands for creating databases, manipulating data, querying, and managing user privileges. Additionally, it covers advanced topics such as exception handling, cursors, and event handling in database management.

Uploaded by

Amaan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

DBMS CODES_PLSQL

The document provides a comprehensive overview of SQL concepts including DDL, DML, DQL, DCL, and various database functionalities like inbuilt functions, aggregate functions, constraints, joins, views, stored procedures, and triggers. It includes practical examples and SQL commands for creating databases, manipulating data, querying, and managing user privileges. Additionally, it covers advanced topics such as exception handling, cursors, and event handling in database management.

Uploaded by

Amaan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Table of contents

1 DDL
2 DML
3 DQL
4 DCL
5 Inbuilt Functions
6 Aggregate functions
7 Constraints
8 Joins
9 Views
10 Stored Procedure
11 Stored Functions
12 If else
13 While loop
14 Events
15 Exception Handling
16 Cursors
17 Triggers
18 PROJECT (REGISTER USING PYTHON WITH DATABASE
CONNECTIVITY)
19 Project on events and Trigger

20 PLSQL
SECTION 1
DDL (Data Defination Language)
1. Create
2. Alter – add, modify, rename , drop
3. Drop
4. Truncate

--create a database
create database person;
use person;

--create a table
create table student (
id int,
name varchar(50),
phno varchar(15),
fees int
);

--Alter
Alter table student add email varchar(50);
Alter table student modify column phno varchar(10);
Alter table student rename column phno to phone_no;
Alter table student drop column email;

--Drop
drop table student;
drop database person;
SECTION 2

DML (Data Manipulation Language)


1. Insert
2. Update
3. Delete
--Use same table as above

--Insert
--Insert All values

insert into student values(121,"Joe","13431681",7000);


insert into student values(122,"Nick","26465146",7000);
insert into student values(124,"Han","34651335",7000);

--Insert specific values


insert into student(id,name) values(125,"Tae ");

--To view all the data from student table


select * from student;

--Update
--Update all the data
update student
set name=” Hanna”;

--Update specific data


update student
set name="hanna", fees=1000
where id =121;
--Delete
--Delete all data
delete from student;

--Delete specific data


delete from student where id = 5;

--Delete in a range
delete from student
where id between 3 and 4;
SECTION 3

DQL (Data Query Language)


1. Select
1.1 from
1.2 order by
• Ascending/descending
1.3 Where
• Relational Operators
• Logical Operators
• Membership Operators(in/not in)
• Between/not Between
• Like (“_”, “%”)

1.4 Limit
--Select
select "Alfina";

--Select & from


use sakila;
desc actor;

select * from actor;

select first_name, last_name from actor;

--Order by
select * from actor order by first_name asc;

select * from actor order by first_name desc;

select * from actor order by first_name, actor_id desc;

--(it will do order by first_name only and will not consider actor_id
while arranging the data)
--where
--Relational Operators
select * from actor where actor_id <100;

select * from actor where actor_id <=100;

select * from actor where actor_id > 100;

select * from actor where actor_id >= 100;

select * from actor where actor_id != 5;

select * from actor where actor_id <> 5;

select * from actor where actor_id = 5;

--Logical Opeartors
select * from actor where first_name = "nick" and actor_id<=100;

select * from actor where first_name = "nick" or actor_id<=100;

select * from actor where not actor_id = 100;

--Membership Operators
select * from actor where actor_id in (1,2,3,4,10,50,100);

select * from actor where first_name in ("nick","penelope","kenneth");

select * from actor where first_name not in ("nick","penelope","kenneth");

select * from actor where first_name in ("nick","penelope","kenneth")


order by actor_id desc;

--between / not between


select * from actor where actor_id between 1 and 10;
select * from actor where actor_id between 1 and 10 or actor_id between 31
and 50;
--Like operator
select * from actor where first_name like "R%";

select * from actor where first_name like "R%" or last_name like "N%";

select * from actor where first_name like "A_E";

select * from actor where first_name like "A_E%";

select * from actor where first_name like "A%E%";

select * from actor where first_name like "%A";

--Limit
use sakila;

select * from actor where actor_id limit 10;

select * from actor where actor_id limit 5 ,10;


SECTION 4

DCL (Data Control Language)


1. Grant
The GRANT command is used to give users access privileges to the database
objects (like tables, views, sequences, etc.)
2. Revoke
The REVOKE command is used to remove access privileges that have been
granted to users.

--First create a user

create user 'hellouser' identified by '123456';

--Now create a new connection

--Click on ‘+’ icon and build a connection and enter the username that you created in
‘Username’.
--Click on ‘Store in vault’ and enter the password that you created

--Then click on ‘OK’ and ‘Test Connection”

--Grant

grant all on actor to 'hellouser';


OR
grant select, insert, delete on actor to 'hellouser';

--Revoke

revoke insert , update, delete on actor from 'hellouser';


SECTION 5
Inbuilt Functions
1. Number function
2. String function
3. Date function
--Number functions
select round(3.36) as result1;

select round(3.3655249,2) as result1;

select ceiling(5.2) as result1;

select floor(5.2) as result1;

select pow(2,2) as result;

select sqrt(49) as result;

select abs(66), abs(-66);

select pi();

select amount as Amount,


round(amount) as Amnt,
round(amount,1) as Amnt1,
floor(amount) as FloorAmnt,
ceiling(amount) as CeilAmnt
from payment;

--String functions
select ascii ('a'), ascii('A');

select char(72, 121, 83,81,76);


select char(65);

select length('SQLAUTHORITY') , length('sqlauthority ');

select ltrim(" hello ");

select ltrim(" hello ");


-- STRCMP - returns 0 if the strings are same
-- retruns -1 if the first arguement is smaller than the second
-- retruns 1 if the first arguement is larger than the second

select strcmp('hello', 'hello'),strcmp('hello', 'world'), strcmp('world', 'hello');

select first_name , last_name , concat(first_name, " ", last_name) as fullname,


reverse(first_name) as rev,
replace(first_name , "E", "$") as rep,
left(first_name , 2) as firstInitials,
right (first_name , 2) as lastInitails,
upper(first_name) as upp,
lower(first_name) as low from actor;

--Date function
-- m = month , d = date , y = 2 digit year , Y= 4 digit year , b= month with 3
character string, t = time , f = pecision of time

select concat(first_name, ' ', last_name) as Fullname,


date_format(last_update, '%m%d%y') as lastupdated1,
date_format(last_update, '%d-%m-%Y') as lastupdated2,
date_format(last_update, '%d %b %Y %T: %f') as lastupdated3
from actor;

-- Distinct operations
-- duplicate records are eliminated

select first_name from actor;

select distinct (first_name) from actor;


SECTION 6

Aggregate functions
1. Min()
2. Max()
3. Avg()
4. Count()
5. Sum()
6. Group by clause
7. Having clause
use sakila;

select * from film;

select min(rental_duration) as minimum,


max(rental_duration) as maximum,
avg(rental_duration) as average,
count(rental_duration) as count1,
sum(rental_duration) as sum1 from film;

--group by
-- will group all the same data and find the aggregate functions of it

select rental_duration, min(rental_duration) as minimum,


max(rental_duration) as maximum,
avg(rental_duration) as average,
count(rental_duration) as count1,
sum(rental_duration) as sum1 from film group by rental_duration;

--having clause
-- it is only used with group by clause

select rental_duration, min(rental_duration) as minimum,


max(rental_duration) as maximum,
avg(rental_duration) as average,
count(rental_duration) as count1,
sum(rental_duration) as sum1 from film group by rental_duration
having count(rental_duration)> 200 ;
SECTION 7
Constraint
1. Primary key (auto_increment)
2. Unique key
3. Default
4. Not null
5. Check

create database demo;


use demo;

create table student (


id int auto_increment,
name varchar(50) not null,
email varchar(50) unique key,
phno varchar(15) unique key,
address varchar(50),
age int default 20,
primary key(id),
check (age > 18)
);

desc student;

insert into student values(1, "Sheetal", "sh@gmail.com", "897065757",


"Andheri", 19);

insert into student(name, email, phno, address, age) values("Hemant",


"h@gmail.com", "8197065757", "Andheri", default);
--error
insert into student(name, email, phno, address, age) values(null,
"h@gmail.com", "8197065757", "Andheri", 9);
SECTION 8
Joins
1. sql joins combine columns from two or more table into a single result
set
2. mysql is a relational database and to have a relation we need more
than one table
3. Types of joins:
3.1 inner join
3.2 Outer Join : -left outer join /right outer join /full outer join
3.3 Cross join
3.4 Self join
3.5 Equi join
3.6 Natural join
4. Inner join returns when there is at least one match in both the tables.
The common operator use in inner joint is "equal to" operator.
5. Left outer join returns all the rows from the left table with matching
rows from the right table
6. If there are no columns matching int the right table it returns NULL
value
7. Right outer join returns all the rows from the right table with
matching rows from the left table
8. If there are no columns matching int the left table it returns NULL
value
9. full outer join combine left outer join and right outer join. this join
returns rows from either table. When the conditions are met and
returns a NULL value when there is no match.
10. my sql does not support full outer join syntax
if you want to stimulate full outer join in mysql use left join and right join
with union */
union operator
Union combines two or more select statement into a single result set
However, the condition is that each select statement of union operator
must have the same number of columns
-- union: It will automatically remove duplicate rows
-- union all: it does not remove duplicate rows and return result as it is we
can use only one order by clause with sort as an entire result set*/
use school;

create table std1(id int primary key auto_increment,


name varchar (50) not null);

insert into std1 values (1, "nashra");

insert into std1 ( name) values ("fazil"),


("asif"), ( "sheban"), ("Muaawiyah"), ("rubiya"), ("habib"), ("nabeela"),
("ayesha"), ("asfiya");

select * from std1;

create table dept(dept_id int primary key auto_increment,


dept_name varchar(50) not null,
s_id int,
foreign key (s_id) references std1(id));

insert into dept values (1,"BCA", 4);

insert into dept(dept_name) values("AUTO_MOBILE");

insert into dept(dept_name , s_id) values ("AIML", 9);

select * from dept;

create table subject1 (sub_id int primary key auto_increment,


sub_name varchar(50) not null);

insert into subject1 values(1, "C");

insert into subject1(sub_name) values("C++"), ("Java"), ("Python"), ("DBMS");

select * from subject1;

-- inner join
select std1.* , dept.* from std1 inner join dept
on std1.id = dept.s_id;

-- left outer join


select std1.* , dept.dept_id, dept.dept_name from std1 left outer join dept
on std1.id = dept.s_id;
-- right outer join
select std1.* , dept.* from std1 right outer join dept
on std1.id = dept.s_id;

-- full join
select std1.* , dept.* from std1 left outer join dept
on std1.id = dept.s_id
union
select std1.* , dept.* from std1 right outer join dept
on std1.id = dept.s_id;

-- cross join
select std1.* , subject1.* from std1 cross join subject1
where subject1.sub_name ="C";
SECTION 9
Views
1. View is commonly known as virtual table, based on the result set of
the sql statement
2. A view is a database object which contain select statement
3. The table reference in the views are known as base table
4. View do not store any data, the data are retrived at runtime from
base table
5. Mysql supports nested views. nested view is a view that is based on
another view
6. Mysql does not support materialized view. a masterialized view
means where view itself store data
7. Advantages of views:
 simplified query
 data security with view
 DML operation with view
--Views
use sakila;

select * from actor;

create view vw_actor as


select actor_id,first_name , last_name from actor;

select * from vw_actor;

select * from vw_actor


where first_name like "A%";

--Nested views
create view vw_actor2 as
select * from vw_actor
where first_name like "A%";

select * from vw_actor2;

select * from vw_actor2


where last_name like "%A%";

--drop the views


drop view vw_actor;

drop view vw_actor2;


Section 10
Stored Procedure
1. A stored procedure is a sub routine available to application that
access a relational database system
2. A stored procedure contains 1 or more sql statements stored in
database
3. Stored procedure is also called as procedure
4. We can use stored procedure parameters to pass 1 or more values
from a calling program
5. There can be input(in) parameter as well as output(out) parameter,
input
6. Advantages of stored procedure:-
 Overhead
 Avoidance of network traffic
 Encapsulation of business logic
--Stored Procedure
use sakila;

select * from actor;

delimiter $$
create procedure actor1()
begin
select * from actor;
end $$
delimiter ;

call actor1();

-- procedure with one parameter


delimiter $$
create procedure actor3(in id int)
begin
select * from actor where actor_id = id;
end $$
delimiter ;

call actor3(6);
call actor3(10);
--procedure with 2 arguments

delimiter $$
create procedure actor4(in f_name varchar(45), in l_name varchar(45))
begin
select * from actor where first_name= f_name and last_name = l_name;
end $$
delimiter ;

call actor4("meg", "hawke");

--drop procedure
Drop procedure actor4;
SECTION 11
Stored Functions
1. A stored function in SQL is a set of SQL statements that perform a
specific task and return a single value.
2. Unlike stored procedure, may or may not return a value, but stored
function will always return a value
3. The terms DETERMINISTIC and NOT DETERMINISTIC are used to describe
the behavior of stored functions in terms of their consistency and
predictability.
4. A DETERMINISTIC function is one that always produces the same output
given the same input parameters.
5. This means that the function's result depends solely on its input values
and does not vary based on other factors like the current date and time
6. A NOT DETERMINISTIC function is one that may produce different
outputs for the same input parameters.

--Stored Functions
--Deterministic
use vl;
delimiter $$
create function calculatetotalsalary (hourly_salary int, hours_worked int)
returns int
deterministic
begin
declare total_salary int;
set total_salary = hourly_salary * hours_worked;
return total_salary;
end$$

select calculatetotalsalary(25, 40) as totalsalary;


Eg2)
create function addnumbers(a int, b int)
returns int
deterministic
begin
return a + b;
end $$

select addnumbers(25, 40) as totalsalary;

--Not Deterministic
create function getcurrentdatetime()
returns datetime
not deterministic
reads sql data
begin
return now();
end$$

select getcurrentdatetime() as currenttime;

Eg2)
create function random_add(n int)
returns int
not deterministic
begin
return n + floor(rand() * 10);
end;
select getcurrentdatetime() as currenttime;
SECTION 12

If else Syntax:
Inside stored procedure
Declare --------
If (condition) Then
Stmts;
Else

Stmts;
End if;
--greater between 2 numbers

use office;

show tables;

delimiter $$
create procedure if1()
begin
declare a int default 15;
declare b int default 20;
if(a>b)
then
select "A is greater" as msg;
else
select "B is greater" as msg;
end if;
end $$
delimiter ;

call if1();
--greater between 2 numbers (call by value)
delimiter $$
create procedure if2(in a1 int , in b1 int)
begin
declare a int default a1;
declare b int default b1;
if(a>b)
then
select "A is greater" as msg;
else
select "B is greater" as msg;
end if;
end $$
delimiter ;

call if1(10,5);

Hw.
1. Check if number is positive or not
2. Check if the number is zero or non zero
3. Check if number is even or odd
4. Check if entered year is leap year or not
5. Check if number is divisible by 3 or not
6. Check if number is divisible 3 and 5 both
SECTION 13
While loop
Syntax:
Inside stored Procedure
------Declare -------
While (condition)
Do
Stmts;
Inc/dec
End while;
--1 to 10
delimiter $$
create procedure whileloop()
begin
declare i int default 1;
while i<=10
do
select i;
set i = i+1;
end while;
end $$
delimiter ;

call whileloop();

--10 to1
delimiter $$
create procedure whileloop1()
begin
declare i int default 10;
while i>=1
do
select i;
set i = i-1;
end while;
end $$
delimiter ;

call whileloop1();
--1 to n
delimiter $$
create procedure whileloop2(in n int)
begin
declare i int default 1;
while i<=n
do
select i;
set i = i+1;
end while;
end $$
delimiter ;

call whileloop2(5);

Hw.
1. n-1
2. 1-10(even and odd)
3. Factorial of 5
4. Sum from 1-10
5. Square from 1-10
6. Sum of Cube from 1-10
7. Table of 5
SECTION 14
Events
1. An event is a block of code that is executed automatically according to
scheduler.
2. MySql supports one time event as well as recurring event.
3. The primary reason to use events to do various maintenance task
related to table.
4. There are two types of events
 one time event
 recurring event
--Events
use school;

set global event_scheduler = ON;

create table message(


id int primary key auto_increment,
message varchar(50),
date1 timestamp default current_timestamp );

insert into message values(1, "Hello", default);

select * from message;

--One time event


delimiter $$
create event event1
on schedule at now() + interval 20 second
do
begin
insert into message (message, date1) values("This is my on time event",
default);
end $$

--Recurring
create event recurringevent1
on schedule every 5 second
starts now()
ends now() + interval 3 minute
do
begin
insert into message(message, date1) values("Thank you for coming", default);
end $$
--Drop an event
drop event recurringevent;

-- truncate table message;

show events;
SECTION 15
Exception handling
1. An error condition during a program execution is called as exception
2. The mechanism for resolving such an exception is exception
handling
3. My sql Supports conditional handler
 Exit handler: Immediately exit the block
 Continue handler: Stored procedure continue the handler. It
allow execution to continue in stored procedure
--Exception handling
use hospital;

create table class(id int primary key, name1 varchar(50) not null);

insert into class values(3, null); -- error code 1048 for not null inserting

insert into class values(3 , "Alfina"); -- error code 1062 for duplicate value

select *from class;

delimiter $
create procedure exception_handle(in id1 int, in value1 varchar(50))

begin
declare flag int default 0;
declare flag1 int default 0;
begin
declare exit handler for 1048 set flag = 1;
declare exit handler for 1062 set flag1 = 1 ;

insert into class values (id1, value1);


select "Successfully inserted value" as message;
select * from class;
end;

if flag =1
then
select "Unsuccessful insert due to null value" as message;
elseif flag1 = 1
then
select "You have inserted duplicate value" as message;
end if;
end $
delimiter ;
call exception_handle(1 , "Umaima");

--Drop procedure
drop procedure exception_handle;
SECTION 16
Cursors
1. A cursor allows to iterate a set of rows return by a query and process
them accordingly.
2. A cursor is a method by which we can assign a name to a result of
select statement and manipulate the data within that sql statement.
3. Example: JDBC, NODEJS, PYTHON
4. Sql, we create cursor inside a stored procedure to handle the result
set return by a query
5. There are 2 types of cursor:
 Implicit Cursor:
Implicit Cursor also known as default cursor. This cursor's are
allocated by sql server when the user perform DML operation.
 Explicit Cursor:
This are created by user whenever the user requires them. Explicit
cursor's are used for fetching data from table in row by row
manner.
6. Steps involved to work with cursor :
 Declare cursor name for select statement.
 Open cursor name initialize the reult set for operation.
 Fetch cursor name into variable list, to retrieve the next row
pointed by the cursor and move the cursor to the next row in the
result set.
 Close cursor name to deactivate the cursor and release any
memory associated with it.
 Deallocate
--Cursors
use office;

create table employee(


empid int primary key,
empname
varchar(50), salary
int);

insert into employee values(1, "Ayman", 100000),


(2, "Abdullah", 740000),
(3, "Arsalan", 850000);

select * from employee;


delimiter $
create procedure cursor2()
begin

---- declaring variables that is will fetch the data from original table and keep it
in their respective temporary variables.

declare EMPID1 INT ;


declare EMPNAME1 varchar(50);
declare SALARY1 int;
declare TOTALSAL1 int default 0;
declare done1 int default 0;

declare emp_cursor Cursor for select empid,empname ,salary from employee;

declare continue handler for not found set done1 = 1;

open emp_cursor;

cursorloop :loop
fetch emp_cursor into EMPID1,EMPNAME1, SALARY1;

if done1 = 1
then
leave cursorloop;
end if;

set TOTALSAL1 = SALARY1 + TOTALSAL1;

end loop cursorloop;

select "The total salary is" as RESULT , TOTALSAL1;

end $

call cursor2;
--Cursor that handle null

use vl;

create table students(sid int primary key,


name varchar(50) ,
fees int);

insert into students values(1,"Saleha", 15000), (2,"Aakash", 10000),


(3,"Nehaal", 11000), (4, "Usman", null), (5, "Aisha", 20000);

select * from students;

drop table students;

update students set fees= 3000 where sid =4;

truncate table students;

delimiter $$
create procedure cursor1()
begin
declare id1 int ;
declare name1 varchar(50);
declare fees1 int;
declare total1 int default 0;
declare done1 int default 0;

declare b_cursor cursor for select sid , name , fees from students;

declare continue handler for not found set done1=1;

open b_cursor;

anusloop:loop
fetch b_cursor into id1, name1, fees1;

if done1 =1
then
leave anusloop;
end if;

set total1 = total1 + IFNULL(fees1, 0);


end loop anusloop;
close b_cursor;
select "Total values " as msg , total1;

end $$
--Call the cursor
call cursor1;
SECTION 17
Triggers
1. When we want to do some work automatically but only when we
perform some operation like insert update and delete.
2. Trigger are executed before or after DML operation. Trigger
execution is often called as trigger firing Trigger must be created
with for each row clause
3. The old key word gets a value from the row that is being updated or
deleted
4. The new keyword gets a value from the row that is being inserted or
updated
5. The are 2 types of trigger :
 Before trigger :
Before trigger always execute before any DML operation.
Mostly used in update and insert.
 After trigger:
After trigger always execute after any DML operation.

--Triggers
use hostel;

create table employees(


empid int primary key auto_increment,
emp_name varchar(50),
emp_surname varchar(50),
hour_salary int,
dept varchar(50));

insert into employees values(1,"Atif", "Shaikh", 2000, "IT");

insert into employees(emp_name,emp_surname,hour_salary)


values("Umaima", "Shaikh", 250);

select * from employees;

alter table employees add salary int after hour_salary;

update employees set salary = hour_salary * 150;

-- update trigger
create trigger before_update
before Update on Employees
for each row
set New.salary= New.hour_salary * 150;
update employees set hour_salary=100
where empid=1;

select * from employees;

-- insert trigger
create trigger before_insert
before insert on employees
for each row
set New.salary= New.hour_salary * 150;

insert into employees(emp_name,emp_surname,hour_salary)


values("Umaima", "Shaikh", 250);

select * from employees;

-- delete trigger
use hostel;

create table expenses1(id int primary key auto_increment,


expense_name varchar(50),
expense_total int);

insert into expenses1(expense_name,expense_total) values ("salaries", 0);

select * from expenses1;

select sum(salary) from employees;

update expenses1 set expense_total=(select sum(salary) from employees )


where id = 2;

create trigger delete_trigger


after delete on employees
for each row
update expenses1 set expense_total=(select sum(salary) from employees )
where id = 2;

delete from employees where empid=2;

select * from expenses1;

--drop trigger
drop trigger delete_trigger;
Section 18
PROJECT (REGISTER USING PYTHON WITH DATABASE CONNECTIVITY)

REGISTER.PY
'''
pip install mysql-connector-python
'''

‘’’pre requisite:
1. create a database in workbench.
2. create a table in workbench.
3. excute the code.
4. write select statement in workbench. '''

import mysql.connector

# Function to create a new user

def register_user(username, password, name, age, gender):


try:
# Connect to MySQL database
conn = mysql.connector.connect(
host="localhost",
user="root",
password="123456",
database="user"
)
cursor = conn.cursor()

# Create table if not exists


cursor.execute('''CREATE TABLE IF NOT EXISTS users
(id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) UNIQUE,
password VARCHAR(255),
name VARCHAR(255),
age INT,
gender VARCHAR(255))''')

# Check if the username already exists


cursor.execute("SELECT * FROM users WHERE username=%s", (username,))
existing_user = cursor.fetchone()

if existing_user:
print("Username already exists. Please choose a different one.")
else:
# Insert new user into the database
cursor.execute("INSERT INTO users (username, password, name, age,
gender) VALUES (%s, %s, %s, %s, %s)",
(username, password, name, age, gender))
conn.commit()

print("User registered successfully.")

except mysql.connector.Error as e:
print("Database error:", e)
finally:
conn.close()

# Function to prompt user for registration input

def register():
print("Welcome to the registration form.")
username = input("Enter username: ")
password = input("Enter password: ")
name = input("Enter your name: ")
age = int(input("Enter your age: "))

# Basic validation for age


if age <= 0:
print("Invalid age. Please enter a valid age.")
return

gender = input("Enter your gender (Male/Female/Other): ").capitalize()

# Basic validation for gender


if gender not in ["Male", "Female", "Other"]:
print("Invalid gender. Please enter Male, Female, or Other.")
return

register_user(username, password, name, age, gender)

# Call the register function


register()
REGISTER.SQL
create database user;
use user;

CREATE TABLE IF NOT EXISTS users


(id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) UNIQUE,
password VARCHAR(255),
name VARCHAR(255),
age INT,
gender VARCHAR(255));

select * from users;


SECTION 19
PROJECT ON EVENT AND TRIGGER
-- create the inventory table
create table inventory (
product_id int auto_increment primary key,
product_name varchar(255),
quantity int,
last_updated datetime default current_timestamp
);

-- create the inventory_log table


create table inventory_log (
log_id int auto_increment primary key,
product_id int,
log_message varchar(255),
log_time datetime default current_timestamp
);

-- create the inventory_archive table


create table inventory_archive (
archive_id int auto_increment primary key,
product_id int,
product_name varchar(255),
quantity int,
archived_date datetime default current_timestamp
);

create trigger before_inventory_insert


before insert on inventory
for each row
insert into inventory_log (product_id, log_message, log_time)
values (new.product_id, concat('inserting product: ', new.product_name, ' with
quantity: ', new.quantity), now());

delimiter //

create event archive_old_inventory


on schedule every 1 minute
starts now()
do
begin

-- insert old inventory items into the archive


insert into inventory_archive (product_id, product_name, quantity,
archived_date)
select product_id, product_name, quantity, now()
from inventory
where last_updated < now() - interval 1 minute;
-- delete the archived items from the inventory
delete from inventory
where last_updated < now() - interval 1 minute;
end//

delimiter ;

insert into inventory (product_name ,quantity,last_updated ) values("wire", 50,


default);

select * from inventory;


select * from inventory_log;

select * from inventory_archive;


SECTION 20
PLSQL simple codes (in sql plus)
1. Before using this package run the command
2. SET SERVEROUTPUT ON

Simple hello world


DECLARE

a varchar2(20):= 'Hello, World!';

BEGIN

dbms_output.put_line(a);

END;

Addition of 2 numbers
declare
a number(10) :=&a;
b number(10) :=&b;
c number(10);
begin
c:=a+b;
dbms_output.put_line('Addition of 2 number is'||c);
end;
/

If else
Greater between 2 numbers
declare
a number(10) :=&a;
b number(10) :=&b;
begin
if (a>b)
then
dbms_output.put_line('A is greater');
else
dbms_output.put_line('B is greater');
end if;

end;
/
Even and odd
declare
a number(10) :=&a;
begin
if mod(a,2)=0
then
dbms_output.put_line('A is even');
else
dbms_output.put_line('A is odd');

end if;

end;
/

If else ladder

If <condition> then
Elsif <condition > then
Else

Greater between 3 numbers


declare
a number(10) :=&a;
b number(10) :=&b;
c number(10) :=&c;

begin
if (a>b and a>c)
then
dbms_output.put_line('A is greater');
elsif (b>c)
then
dbms_output.put_line('B is greater');
else
dbms_output.put_line('C is greater');

end if;

end;
/
LOOPING

BASIC LOOP / EXIT LOOP


declare

i number := 1;

begin

loop

exit when i>10;

dbms_output.put_line(i);

i := i+1;

end loop;

en/
/

While loop
declare

i number := 1;

begin

while i <= 10
loop

dbms_output.put_line(i);

i := i+1;

end loop;

end;

/
Factorial
declare

i number := 1;
fact number:=1;
n number:=&n;

begin

while i <= n
loop
fact := fact*i;
dbms_output.put_line(fact);

i := i+1;

end loop;

end;

For loop
declare

a number;

begin

a:=10;

for a in 1..10

loop

dbms_output.put_line(a);

end loop;

end;

/
Cursors
Declare, open, fetch and close
1. create a table
-- assume we have a table called employees
create table employees (
employee_id number primary key,
first_name varchar2(50),
last_name varchar2(50),
salary number
);

2. insert some values


-- insert some sample data
insert into employees values (1, 'john', 'doe', 50000);
insert into employees values (2, 'jane', 'smith', 60000);
insert into employees values (3, 'emily', 'jones', 70000);
insert into employees values (4, 'michael', 'brown', 55000);
insert into employees values (5, 'linda', 'davis', 65000);
commit;

3. create a explicit cursor


-- pl/sql block using a cursor
declare
-- declare a cursor to select employee details
cursor emp_cursor is
select employee_id, first_name, last_name, salary
from employees;

-- declare variables to hold the fetched values


-- using %type ensures these variables have the same data type as the
columns
v_employee_id employees.employee_id%type;
v_first_name employees.first_name%type;
v_last_name employees.last_name%type;
v_salary employees.salary%type;
begin
-- open the cursor
open emp_cursor;

-- fetch each row from the cursor


loop
fetch emp_cursor into v_employee_id, v_first_name, v_last_name,
v_salary;

-- exit the loop if no more rows are found


exit when emp_cursor%notfound;
-- process the fetched data (for demonstration, we just output it)
dbms_output.put_line('employee id: ' || v_employee_id || ', name: ' ||
v_first_name || ' ' || v_last_name || ', salary: ' || v_salary);
end loop;

-- close the cursor


close emp_cursor;
exception
when others then
-- handle any exceptions
dbms_output.put_line('an error occurred: ' || sqlerrm);
end;
/
Trigger
1. -- create a table
create table employees(
empid number(10) primary key,
emp_name varchar(50),
emp_surname varchar(50),
hour_salary number(10),
dept varchar(50));

2. -- insert some values


insert into employees values(1,'Atif', 'Shaikh', 2000, 'IT');
insert into employees values(2,'Asfiya', 'Shaikh', 3000, 'IT');
insert into employees values(3,'Alfina', 'Shaikh', 4000, 'IT');
insert into employeesvalues(4,'Aisha', 'Shaikh', 5000, 'IT');

alter table employees add salary number after hour_salary;

update employees set salary = hour_salary * 1500;

3. -- Create or replace the trigger

CREATE OR REPLACE TRIGGER trg_before_update_employees


BEFORE UPDATE ON employees
FOR EACH ROW
BEGIN
-- Set the new salary based on hour_salary * 1500
:NEW.salary := :NEW.hour_salary * 1500;
END;
/

You might also like