You are on page 1of 64

St.

JOSEPH'S INSTITUTE OF TECHNOLOGY


(St.Joseph’s Group of Institutions)
OMR, CHENNAI – 119

We Make You Shine

DEPARMENT OF COMPUTER SCIENCE AND


ENGINEERING

Name : ASHIN VELT V H

Year : II Semester: IV

Branch : CSE

Reg. No : 312419104020

Lab Code : CS8461

LAB Name:OPERATING SYSTEM LABORATROY


1
St.JOSEPH’S INSTITUTE OF TECHNOLOGY

(St.Joseph’s Group of Institutions)

OMR, CHENNAI - 119.

BONAFIDE CERTIFICATE

This is a certified bonafide record book of AJAY GANESH R T Register No.


312419104005submitted for the University Practical Examinations held on _____________ in
_Database Management Systems _ Laboratory / Workshop during the year 2021/ 2022 .

LAB HOD
LAB IN-CHARGE
DATE:
DATE:

LAB HOD
LAB IN – CHARGE
DATE :
DATE :

INTERNAL EXAMINER EXTERNAL EXAMINER

DATE: DATE :

INTERNAL EXAMINER

DATE :

2
INDEX
Name of the Lab: CS8481/DBMS Name of the Staff:
Date of
S.No. Name of the Experiment Page No.
Exp.
Data Definition Commands, Data Manipulation
1. 25.02.21 Commands for inserting, deleting, updating and 4 To 11
retrieving Tables and Transaction Control statements
Database Querying – Simple queries, Nested queries,
2. 04.03.21 12 To 21
Sub queries and Joins

3. 11.03.21 Views, Sequences, Synonyms 22 To 24

4. 11.03.21 Database Programming: Implicit and Explicit Cursors 25 To 27

5. 18.03.21 Procedures and Functions 28 To 31

6. 05.04.21 Triggers 32 To 33

7. 12.04.21 Exception Handling 34 To 36

Database Design using ER modeling, normalization


8. 19.04.21 37 To 44
and Implementation for any application
26.04.21
9. Database Connectivity with Front End Tools 45 To 49
03.05.21

10. 10.05.21 Login System 50 To 64

3
Exp.No:1DATA DEFINITION COMMANDS, DATA MANIPULATION
COMMANDS FOR INSERTING, DELETING, UPDATING AND RETRIEVING
TABLES AND TRANSACTION CONTROL STATEMENTS

AIM:
To design and implement a database for manipulating & storing data items in Oracle by using SQL
commands.

CREATE: (Syntax)
Database:
Create database <database name>;
Use <database name>;
Table:
Create table <table name> (column_name1 datatype1 constraints, column_name2 datatype2
constraint....column_nameNdatatypeN constraints);

Note: Constraints is optional


DDL COMMANDS:
1) Create
2) Alter
✓ Add
✓ Modify
✓ Drop
3) Rename
4) 4) Drop
ALTER:
ADD:
Alter table<table name>add column_name1 datatype1 constraints;
MODIFY:
Alter table<table name>modify column_name1 datatype1;
DROP:
Alter table<table name>drop column_name;
RENAME:
Rename table <old table name>to<new table name>;
DROP:
Drop table<table name>;
DML COMMANDS:
1) Insert 3) Select
2) Update 4) Delete
INSERT:
Insert into<tablename>values(Value1,value2…….ValueN);
SELECT:
Select<column name>from<table name> where condition;
UPDATE:
Update<table name>set<column name>=values where condition;
DELETE:
Delete from<table name> where condition;
TCL COMMANDS:
1) Commit
2) Rollback

4
3) Savepoint
COMMIT:
Commit;
ROLLBACK:
Rollback to <savepoint>;
SAVEPOINT:
Savepoint<savepoint name>;

PROBLEM STATEMENT:

➢ A branch contains many accountholders.


➢ A branch provides more than one loan.
➢ A loan can be availed by more than customer.
➢ A customer can get more than one loan.
➢ A customer can have more one account.
➢ An account can have more than one customer.

1. TABLE FROM THE PROBLEM STATEMENT:


1) Branch_m
2) Account_m
3) Loan_m
4) Customer_m

Table Name:Branch_m
> create table branch_m(branch_name varchar(20) primary key,branch_city varchar(20),asset int);

Table name: Customer_m


sql> create table customer_m(customer_id varchar(20) primary key,customer_name
varchar(20),customer_street varchar(20),customer_city varchar(20));

sql> desc customer_m;

Table name: Account_m

sql> create table account_m(account_no varchar(20) primary key,branch_name varchar(20),balance


int,foreign key(branch_name) references branch(branch_name));

Table name: Loan_m


sql> create table loan_m(loan_no varchar(20) primary key,branch_name varchar(20),amount
int,foreign key(branch_name) references branch(branch_name));

5
sql> desc loan_m;

2.Alter the table branch_m by increasing the field width of branch city to 25.
SQL>desc branch_m;
sql> alter table branch_m modify branch_cityvarchar(25);

sql> desc branch_m;

3.Drop the primary key from loan_m

sql> desc loan_m;

sql> alter table loan_mdrop primary key;

sql> desc loan_m;

4.Alter the primary key to loan_m

sql> desc loan_m;

6
sql> alter table loan_madd primary key(loan_no);

sql>Table LOAN_M altered.

5.Add new column to loan_m.

sql> alter table loan_m add roiNUMBER(3);


sql>Table LOAN_M altered.

sql> desc loan_m

6.Drop the column from loan_m


sql>alter table loan drop column loan_no;

sql> desc loan_m;

7. Rename the customer_m as customer_ma

sql> rename customer_mtocustomer_ma;

sql> desc customer_m;


ERROR:
ORA-04043: object customer_m does not exist

sql> desc customer_ma;

7
8)a) Drop customer_ma

sql> desc customer_ma;

sql> drop table customer_ma;


sql> Table dropped

sql> desc customer_ma;


ERROR:
ORA-04043: object customer_ma does not exist

9. INSERTRECORDS IN ALL THE FOUR CREATED TABLES:


Insert the values given below.(Branch Table)
BRANCH_NAME BRANCH_CITY ASSETS

Perryridge Rye 50000


Downtown Stamford 100000
Brighton Paloalto 25000
Redwood Harrison 150000
Mianus Pitsfield 450000
Roundhill Princeton 150000

sql> insert into branch_m values('perryridge','rye',50000);

Insert the values given below. (Loan Table)


LOAN BRANCH_NAME AMOUNT

1_11 Roundhill 900


1_14 Downtown 1500
1_15 Perryridge 1500
1_16 Perryridge 1300
1_17 Downtown 1000
1_23 Redwood 2000

8
1_93 Mianus 500
l_102 Mianus Null

Insert the values given below. (Customer Table)


CUSTOMER_I CUSTOMER_NAM CUSTOMER_STREE CUSTOMER_CIT
D E T Y
c_01 Smith north rye
c_02 Turner putnam stamford
c_03 Johnson alma paloalto
c_04 Curry north rye
c_05 Jones main harrisdon
c_06 Adoms spring pittsfield
c_07 Lindsay park pittsfeild
c_08 Hayes main harrison
c_09 Williams nassu princeton

sql> desc customer_a;

sql>insert into customer_mvalues('c_01','smith','north','rye');

Insert the values given below. (Account Table)


ACCOUNT_NO BRANCH_NAME BALANCE

019_28_3746 Perryridge 1500


182_73_6091 Downtown 1800
192_83_7465 Brighton 500 sql>desc account_m;
321_12_3123 Redwood 2300
336_96_9999 Mianus 500
963_96_3963 Roundhill 500
376_66_9999 Mianus 900
963_96_3964 Mianus 1300

9
10. Find the names of all branches in loan relation.
sql> select branch_name from loan_m;
BRANCH_NAME
Perryridge
Downtown
Brighton
Redwood
Mianus
Roundhill
Mianus
Mianus

11. Find the names of all branches in loan relation by eliminating duplicate values.
.
sql> select distinct branch_name from loan_m;

BRANCH_NAME
Roundhill
Downtown
Perryridge
Redwood
Mianus

12.Updatethe customer city stamford to rye in customerrelation.


sql> update customer_m set customer_city='rye' where customer_city='stamford';

sql>commit;

13.Delete records from loan table

sql> select * from loan_m;

LOAN BRANCH_NAME AMOUNT

1_11 Roundhill 900


1_14 Downtown 1500
1_15 Perryridge 1500
1_16 Perryridge 1300
1_17 Downtown 1000
1_23 Redwood 2000
1_93 Mianus 500
l_102 Mianus Null

sql>savepoint s1;

10
savepoint created.

sql> delete from loan_m;

sql> select * from loan_m;


sql> 0 rows selected

sql> rollback to s1;

sql> select * from loan_m;

LOAN BRANCH_NAME AMOUNT

1_11 Roundhill 900


1_14 Downtown 1500
1_15 Perryridge 1500
1_16 Perryridge 1300
1_17 Downtown 1000
1_23 Redwood 2000
1_93 Mianus 500
l_102 Mianus Null
sql>commit;

Result:
Thus the SQL commands have been executed and the output was verified successfully.

11
Exp. No:2 DATABASE QUERYING – SIMPLE QUERIES, NESTEDQUERIES,
SUB QUERIES AND JOINS
DATE:04.03.21

AIM:

To implement and execute a query for manipulating & storing dataitems in sql
database using Structured Query Language commands

DIFFERENT TYPES OF SQL JOINS

• (INNER) JOIN: Returns records that have matching values in bothtables


• LEFT (OUTER) JOIN: Returns all records from the left table, and the matched
records from the right table
• RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched
records from the lefttable
• FULL (OUTER) JOIN: Returns all records when there is a match in either left or
righttable

Consider the two tables below:


Student Course

(INNER) JOIN

SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE


FROM Student INNER JOIN StudentCourse
ON Student.ROLL_NO = StudentCourse.ROLL_NO;

12
Output:

LEFT (OUTER) JOIN

SELECT
Student.NAME,StudentCourse.COURSE_I
D FROM Student
LEFT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Output:

RIGHT (OUTER) JOIN

SELECT
Student.NAME,StudentCourse.COURSE_I
D FROM Student
RIGHT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;

13
Output:

FULL (OUTER) JOIN:

SELECT
Student.NAME,StudentCourse.COURSE_I
D FROM Student
FULL JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;

14
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

Output:

SIMPLE QUERIES
1. Display the loan relation with attributes amount multiplied by 100.
sql> select amount*100 from loan_m;
+ +
| amount*100|

+ +
| 90000 |
| 150000 |
| 150000 |
| 130000 |
| 100000 |
| 200000 |
| 50000 |

7 rows in set

2. Find all numbers for loan made at perryridge branch with loan
amount greaterthan 1400.
sql> select loan_no from loan_m where branch_name='perryridge' and
amount>1400;
+ +
| loan_no|
+ +

15
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

|l_15 |
+ +
1 row in set

3. Find all loan numbers for loan’s with loan amount between 900 and1500.
sql> select loan_no from loan_m where amount between 900 and 1500;

+ +
| loan_no|
+ +
|l_11 |
|l_14 |
|l_15 |
|l_16 |
|l_17 |
+ +
5 rows in set

4. Find the names of customer of customer whose street names


includes the character rin the thirdposition.
sql> select customer_name from customer_m where
customer_street like'r%';
+ +
| customer_name|
+ +
|smith |
|curry |
|adoms |
+ +
3 rows in set (0.00 sec)

16
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

5. Find the names of customer_m whose street name starts


with substring ‘ma’. sql> select customer_name from
customer_m where customer_streetlike'ma%';
+--------------------+
| customer_name|
+ +
|williams |
+ +
1 row in set
6. Display the entire loan relation in descending order ofamount.
sql> select * from loan_m order by amount desc;
+ + + +
| loan_no | branch_name | amount|
+ + + +
|l_23 |redwood | 2000|
|l_14 |downtown | 1500|
|l_15 |perryridge | 1500|
|l_16 |perryridge | 1300|
|l_17 |downtown | 1000|
|l_11 |roundhill | 900|
|l_24 |mianus | 500|
+ + + +

7 rows in set

7. Find total number ofcustomer.


sql> select count(customer_id) from customer_m;
+ +
| count(customer_id)|

17
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

+ +
| 6|
+ +

1 row in set

8. Find all the loan number that appears in the loan relation
with NULL values for amount.
sql> select loan_no from loan_m where amount is null;
+ +
| loan_no|
+ +
|l_102 |
+ +
1 row in set

9. sql> select * from customer_m wherecustomer_id=’c_02’;


+ -+- + +
-+
| customer_id | customer_name | customer_street | customer_city|
+ -+- + +
-+
|c_02 |turner |putnam | rye
|
+ -+- + +
-+
1 rows in set (0.00 sec)

NESTED and SUB QUERIES:

1. Findallthenameofallbranchesthathaveassetsgreaterthanatleastone
bank located in Stanford. (Nestedqueries)
sql> Select branch_name from branch_ma where assets >ANY (select
assetsfrom branch_ma where branch_city='stanford'); BRANCH_NAME

18
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

R
e
d
w
o
o
d
M
i
a
n
u
s
R
o
u
n
d
h
i
l
l

2. Displaytheentirecustomernameinalphabeticalorderthathav
eloanin Perryridge.(Nested queries).

sql> Select customer_name from customer_ma where customer_id=ANY


(
select customer_id from borrow_ma where borrow_ma.loan_no=ANY(
select loan_no from loan_ma where branch_name='Perryridge')) order by
customer_ma.customer_nameasc;

CUSTOMER_NAME

Johnson

3. Find all customer having both account and loan at same


branch.(Nestedqueries)

19
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

sql> Select depositor_ma.customer_id from depositor_ma where


customer_id IN (select borrow_ma.customer_id from borrow_ma);
CUSTOMER_ID

c
_
0
3
c
_
0
5

4. Findallcustomerswhohaveloanatbankbutwhodon’thaveaccountatsame
branch.(Nested queries).

sql> Select borrow_ma.customer_id from borrow_ma where customer_id


NOT IN (

select depositor_ma.customer_id from depositor_ma);

CUSTOMER_ID

c
_
0
1
c
_
0
1

5. Findthenameofallbranchesthathaveassetsgreaterthanthoseatle
astone branch located in Harrison.(Nestedqueries).

sql> Select branch_name from branch_ma whereassets>any(select assets


from branch_ma

20
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

where branch_city='Harrison');

BRANCH_NAME

Mianus

Result:

Thus, The SQL commands have been executed and the output was verified
successfully.

21
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

EXP.NO:3- VIEWS,SEQUENCE AND SYNONYM

AIM:
To implement and execute view,sequence,indexes,savepoint in using SQL commands.

VIEWS:
Create view <viewname> as any select query; (Ex: select * from <tablename> where
<condition>)

SEQUENCE:
Create table <tablename> (column1 datatype1primary key auto_increment,column2 datatype
2……columnNdatatypeN)

SYNONYM:
Create synonym<synonym name> for <table name>;
VIEWS:
1) Create a view using aggregate functions to calculate the age of the Person
sql> create table person_m(name varchar(20) primary key,dobdate,person_city varchar(20));

sql> desc person_m;


| Field | Type | Null | Key | Default | Extra |

| name | varchar(20) | NO | PRI | NULL | |


| dob | date | YES | | NULL | |
| person_city | varchar(20) | YES | | NULL | |
sql> insert into person_m values('abdulkalam','1931-08-18','rameshwaram');
sql> select * from person_m;
| name | dob | person_city |
| abdulkalam | 1931-10-15 | rameshwaram |
| maheshboobathy | 1974-07-02 | chennai |
| sachin | 1973-05-04 | mumbai |
| viswanathanand | 1970-03-06 | chennai |
sql> create view personage_m as select name,datediff(sysdate(),dob)/365.25 as age from
person_m;
sql> select * from personage_m;
| name | age |
| abdulkalam | 83.9726 |
| maheshboobathy | 41.1006 |
| sachin | 42.2615 |
| viswanathanand | 45.4237 |

sql> insert into person_m values('jorden','1970-07-08','usa');

sql> select * from personage_m;


| name | age |
| abdulkalam | 83.9726 |

22
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

| jorden | 45.0842 |
| maheshboobathy | 41.1006 |
| sachin | 42.2615 |
| viswanathanand | 45.4237 |

SEQUENCE:
2) Create a sequence and design the department table in the given attribute.

sql> create table department_m(department_id int primary key auto_increment,department_name


varchar(20));

sql>descdepartment_m;

| Field | Type | Null | Key | Default | Extra |


| department_id | int(11) | NO | PRI | NULL | auto_increment |
| department_name | varchar(20) | YES | | NULL | |
+-----------------+-------------+------+-----+---------+----------------+

sql> insert into department_m(department_name)values('it');


sql> insert into department_m(department_name)values('cse');
sql>insert into department_m(department_name)values('mechanical');
sql> insert into department_m(department_name)values('aero');

sql> select * from department_m;


| department_id | department_name |
| 1 | it |
| 2 | cse |
| 3 | mechanical |
| 4 | aero |

SYNONYM(UsingOracle)

3) Show the effect of synonym


CREATING A SYNONYM FOR A TABLE

CREATE TABLE product_m (product_nameVARCHAR2(25) PRIMARY KEY,


product_price NUMBER(4,2), quantity_on_hand NUMBER(5,0), last_stock_date DATE);
Table created.

AFTER INSERTING THE RECORDS TO PRODUCT TABLE

SQL> SELECT * FROM product_m;


PRODUCT_NAME PRODUCT_PRICE QUANTITY_ON_HAND LAST_STOC
------------------------- -------------------------- ------------------------------ ------------------

23
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

Product 1 99 1 15-JAN-03
Product 2 75 1000 15-JAN-02
Product 3 50 100 15-JAN-03
Product 4 25 10000 14-JAN-03
Product 5 9.95 1234 15-JAN-04
Product 6 45 1 31-DEC-08
6 rows selected.

SQL> SELECT * FROM prod_m;


SELECT * FROM prod_m
*
ERROR at line 1:
ORA-00942: table or view does not exist
SQL> CREATE SYNONYM prod_m FOR product_m;
Synonym created.

SQL> SELECT * FROM prod_m;


PRODUCT_NAME PRODUCT_PRICE QUANTITY_ON_HAND LAST_STOC
------------------------- -------------------------- ------------------------------ ------------------
Product 1 99 1 15-JAN-03
Product 2 75 1000 15-JAN-02
Product 3 50 100 15-JAN-03
Product 4 25 10000 14-JAN-03
Product 5 9.95 1234 15-JAN-04
Product 6 45 1 31-DEC-08
SQL> drop SYNONYM prod_m;
Synonym dropped.

SQL> drop table product_m;


Table dropped.
Result:

Thus, The SQL commands have been executed and the output was verified successfully.

24
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

Ex.No.4 DATABASE PROGRAMMING: IMPLICIT AND EXPLICIT


CURSORS
AIM:

To implement and execute cursor in sql using Procedural Language concepts.

Cursor:A cursor is a pointer to this context area. PL/SQL controls the context area through a
cursor. A cursor holds the rows (one or more) returned by a SQL statement. The set of rows the
cursor holds is referred to as the active set.

There are two types of cursors −


• Implicit cursors
• Explicit cursors
SYNTAX:

IMPLICIT CURSOR:

Sql%attribute name
Where attribute name can be FOUND, NOT FOUND, ISOPEN, %ROWCOUNT

EXPLICIT CURSOR:

Creating an explicit cursor


CURSOR <cursor_name> IS select_statement;

Opening the Cursor


OPEN <cursor_name>;

Fetching the Cursor


FETCH <cursor_name>INTO attributes;

Closing the Cursor


CLOSE <cursor_name>;

IMPLICIT CURSOR (in Oracle)

update the customer table and increase the salary of each customer by 500

sql>SET SERVEROUTPUT ON

CREATE TABLE CUSTOMERS(


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),

25
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

SALARY DECIMAL (18, 2),


PRIMARY KEY (ID)
);
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (3, 'kaushik', 23, 'Kota', 2000.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (6, 'Komal', 22, 'MP', 4500.00 );

DECLARE
total_rowsnumber(2);
BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected ');
END IF;
END;
/
6 customers selected

sql>Select * from customers;

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2500.00 |
| 2 | Khilan | 25 | Delhi | 2000.00 |
| 3 | kaushik | 23 | Kota | 2500.00 |
| 4 | Chaitali | 25 | Mumbai | 7000.00 |
| 5 | Hardik | 27 | Bhopal | 9000.00 |

26
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

| 6 | Komal | 22 | MP | 5000.00 |
+----+----------+-----+-----------+----------+

EXPLICIT CURSOR:
DECLARE
c_idcustomers.id%type;
c_namecustomers.name%type;
c_addrcustomers.address%type;
CURSOR c_customersis
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customersintoc_id,c_name,c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id||' '||c_name||' '||c_addr);
END LOOP;
CLOSE c_customers;
END;
/

1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP

Result:

Thus the SQL / PLSQL commands have been executed and the output was verified
successfully.

27
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

Ex.No.5 PROCEDURES AND FUNCTIONS


AIM:

To implement and execute Procedures and functions in Mysql using Procedural


Language concepts.

PROCEDURES: Procedure is a sub program used to perform an action. Replace-recreates the


procedure if it already exists.
3 MODES:
1) IN – Means you must specify a value for the argument at the time execution of the
procedure.
2) OUT-passes back a value to its calling program.
3) INOUT – When calling the procedure, yu must specify the value and that procedures
passes value back to the calling procedure.
SYNTAX:

Create procedure <procedure_name> (argument {in, out, in out} data type) is


Variable declaration
Begin
Pl/SQL Subprogram body.
End;
FUNCTION: A function is a sub program that accepts argument and returns a unique value to
the caller.

SYNTAX :

Create function <function_name> (parameter) return <data type> is


Variable declaration
Begin
Pl/SQL Subprogram body.
Return statement
End;

1. Procedures:
Create a procedure to find minimum of two numbers
DECLARE
a number;
b number;
c number;
PROCEDURE findMin(x IN number, y IN number, z OUT number) IS
BEGIN
IF x < y THEN

28
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

z:= x;
ELSE
z:= y;
END IF;
END;
BEGIN
a:=23;
b:=45;
findMin(a, b, c);
dbms_output.put_line(' Minimum of (23, 45) : '|| c);
END;
/
Output: Minimum of (23, 45) : 23
Create a procedure to find square of a number
DECLARE
a number;
PROCEDURE squareNum(x IN OUT number) IS
BEGIN
x := x * x;
END;
BEGIN
a:=23;
squareNum(a);
dbms_output.put_line(' Square of (23): '|| a);
END;
/
Output: Square of (23): 529
Create a procedure to update the phone number to customer table

Procedure
---------
create table customer_m (cust_id int primary key,cust_name varchar2(20),cust_phone
number(4));
insert into customer_m (cust_id,cust_name) values(201,'raja');
insert into customer_m (cust_id,cust_name) values(202,NULL);
CREATE or REPLACE PROCEDURE c(ph IN NUMBER,cid IN number) IS
name varchar2(20);
BEGIN
select cust_name into name from customer_m where cust_id=cid;
IF name is NULL then
dbms_output.put_line('Name is not there');
ELSE
update customer_m set cust_phone=ph where cust_id=cid;
END IF;

29
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

END;
/

EXECUTE c(66,201);
select * from customer_m;
CUST_ID CUST_NAME CUST_PHONE
201 raja 66
202 ravi -

EXECUTE c(54,202);

| Name is not there |

2. Functions
Create a function to return the total number of CUSTOMERS in the customers table.
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (3, 'kaushik', 23, 'Kota', 2000.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (6, 'Komal', 22, 'MP', 4500.00 );

CREATE OR REPLACE FUNCTION totalCustomers


RETURN number IS

30
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

total number(2) := 0;
BEGIN
SELECT count(*) into total FROM customers;
RETURN total;
END;
/

Calling a Function
DECLARE
c number(2);
BEGIN
c := totalCustomers();
dbms_output.put_line('Total no. of Customers: ' || c);
END;

Total no. of Customers: 6

RESULT:
Thus, The SQL / PLSQL commands have been executed and the output was verified
successfully.

31
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

Ex.No.6 TRIGGERS
AIM:

To implement and execute triggers and functions using Procedural Language concepts.
TRIGGERS:
1) Trigger is a special type of procedure that the oracle executes when an insert,
modify or delete operation is performed against a given table.
2) It is a stored sub program associated with a table.
3) It is used to keep an audit trial of a table, to prevent invalid transaction, enforce
complex security authorization, to generate data automatically.

SYNTAX FOR TRIGGER

CREATE TRIGGER <TRIGGER NAME>


{BEFORE/AFTER}
{INSERT/UPDATE/DELETE}
ON <TABLENAME>
REFRENCECING {OLD AS OLD /NEW AS NEW}
[FOR EACH STATEMENT /FOR EACH ROW [WHEN <CONDITION>]]
DECLARE
Variable declaration
Constant declaration
BEGIN
PL/SQL Sub program body.
END;

1) Create a trigger to fire for INSERT or UPDATE or DELETE operations


performed on the CUSTOMERS table. This trigger will display the salary
difference between the old values and new value

CREATE TABLE CUSTOMERS(


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)

32
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

VALUES (3, 'kaushik', 23, 'Kota', 2000.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (6, 'Komal', 22, 'MP', 4500.00 );

CREATE OR REPLACE TRIGGER display_salary_changes


BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (7, 'Kriti', 22, 'HP', 7500.00 );
UPDATE customers
SET salary = salary + 500
WHERE id = 2;

RESULT:
Thus, The SQL / PLSQL commands have been executed and the output was verified
successfully.

33
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

Ex.No.7 EXCEPTION HANDLING

AIM:
To implement and execute PL/SQL Block that handles all types of exceptions in Oracle
Database using Procedural Language concepts.

SYNTAX
DECLARE
Variable declaration
BEGIN
Program Execution
EXCEPTION
Exception handling
END;

ZERO_DIVIDE EXCEPTION
SQL> BEGIN
2 DBMS_OUTPUT.PUT_LINE(1 / 0);
3 END;
4 /
BEGIN
*
ERROR at line 1:
ORA-01476: divisor is equal to zero
ORA-06512: at line 2
------------------------------------------------------
BEGIN
DBMS_OUTPUT.PUT_LINE(1 / 0);
EXCEPTION
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE('Division by zero');
END;
/
Division by zero
PL/SQL procedure successfully completed.

DECLARE
a int:=10;
b int:=0;
answer int;

BEGIN
answer:=a/b;
dbms_output.put_line('the result after division is'||answer);

exception
34
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

WHEN zero_divide THEN


dbms_output.put_line('dividing by zero please check the values again');
dbms_output.put_line('the value of a is '||a);
dbms_output.put_line('the value of b is '||b);
END;

dividing by zero please check the values again


the value of a is 10
the value of b is 0

INVALID_NUMBER EXCEPTION
create table student(g_id int , g_name varchar(20), marks int);
insert into student values(1, 'Suraj',100);
insert into student values(2, 'Praveen',97);
insert into student values(3, 'Jessie', 99);
BEGIN
INSERT INTO student(g_id)VALUES('101x');
EXCEPTION
WHEN INVALID_NUMBER THEN
DBMS_OUTPUT.PUT_LINE('Conversion of string to number failed');
END;
/
Conversion of string to number failed
PL/SQL procedure successfully completed.

NO_DATA_FOUNDEXCEPTION
DECLARE
temp varchar(20);

BEGIN
SELECT g_id into temp from student where g_name='Joseph';

exception
WHEN no_data_found THEN
dbms_output.put_line('ERROR');
dbms_output.put_line('there is no name as');
dbms_output.put_line('Joseph in Student table');
end;

TOO_MANY_ROWS:
DECLARE
temp varchar(20);

BEGIN

-- raises an exception as SELECT

35
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

-- into trying to return too many rows


SELECT g_name into temp from student;
dbms_output.put_line(temp);

EXCEPTION
WHEN too_many_rows THEN
dbms_output.put_line('error trying to SELECT too many rows');

end;

OTHERS EXCEPTION
1 BEGIN
2 DBMS_OUTPUT.PUT_LINE(1 / 0);
3 EXCEPTION
4 WHEN OTHERS THEN
5 DBMS_OUTPUT.PUT_LINE('An exception occurred');
6* END;
7 /
An exception occurred
PL/SQL procedure successfully completed.

RESULT:
Thus, The SQL / PLSQL commands have been executed and the output was verified
successfully.

36
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

Ex.No.8 Database Design using ER modeling, normalization and


Implementation for any application
Aim:
To design a database using ER modeling and Normalization for student portal and sports meet
Application

Problem Statement: ER Diagram


• A College is conducting a sports meet.
• Teams from recognized colleges are allowed.
• A team should have the players of same college.
• A player can play for more than one team.
• Events occurs in various grounds in the college.
• Winning teams receive awards.
• A captain is a player of a team.
• A player is a student of a college.
• Many teams can play a game.
• A game takes place in a ground.
• A college can have many teams.
• Only first two teams are awarded.
IDENTIFICATION OF ENTITY:

✓ COLLEGE
✓ PLAYERS
✓ TEAMS
✓ GAMES
✓ GROUND
✓ AWARDS
DESCRIPTION ABOUT ENTITY:

37
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

ATTRIBUTES:

✓ COLLEGE – CID, Name, Address line1, Address line2


✓ PLAYERS – FN, LN, POS, DOB, GENDER, PID
✓ TEAM - TID, Name, NOP, Rank, Team
✓ GAMES - GID, Name
✓ GROUND - ID, Name, Area
✓ AWARDS – Name, Position, Prize, Team

DESCRIPTION ABOUT ATTRIBUTES:


COLLEGE

PLAYERS

38
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

AWARDS

GROUN
D

TEAMS

GAMES

RELATIONSHIP:
BINARY:
• Plays
• Has
• Student of
• Receives
• Takes place

39
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

ATTRIBUTES IN THE RELATIONSHIP:

✓ Student of – CID, PID


✓ Has – TID, CID
✓ Plays – TID, GID
✓ Takes place – GID, ID
✓ Receives – TID, Position
CARDINALITY AND RELATIONSHIP:
➢ ONE TO ONE:Plays, Takes place
➢ MANY TO ONE:Student of
➢ ONE TO MANY:has
CARDINALITY ABOUT RELATIONSHIP:
✓ PLAYERS STUDENT OF COLLEGE.
✓ MANY TEAMS PLAY A GAME.
✓ A GAME TAKES PLACE IN A GROUND.
✓ A COLLEGE HAS MANY TEAMS.
ER DIAGRAM:

40
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

CON

NA NO.
CI TI G
TI
RANK

H N TEAMS 1 PL 1 GAMES
CON
1
T G
TAKES
NA I
1 RE

CI
COLLEG POSIT
1 1 ID
ADD GROUN NA

LI LI
AWA AR

CI STU N PLAYER N CA

PI
1 CA

A
Problem Statement: Normalization
Createacollegedatabasethatcontainsstudentid,studentname,studentcity,dateofbirth,cou
rse id, course name, duration of the course, marks and grade and their relationships.
The requirements are listedbelow:
• A college can offer one or morecourses.
• A student can enroll in one or morecourses.
• Courses can be taken by one or morestudents.
• A student can have student_id, student_name, date _of _birth andstudent_city.
• A student belongs to onecity.
• A city can have one or morestudents.
• A course can have course_id, course_nameandduration.
• When a student finishes the course, a grade and marks areawarded.
• Grades are calculated based on themarks
Below 45 – U, 45-50 – E, 50-60– D, 60-70 – C, 70-80 – B, 80-90 – A, 90-100 –S

41
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

FIRST NORMAL FORM

A relation is said to be in first normal form if and only if


*All the attributes in the relation must be atomic in nature.
*No multivalued and composite attributes in the table

In a given table there is no multivalued and composite attributes, so it is satisfying normal


form1

SECOND NORMAL FORM

A relation is said to be in second normal form if and only if


*It is in the first normal form and
*No partial dependencies exist between non-key attributes and key attributes.

STUDEN STUDEN STUDEN DOB COURS COURS DURATION MARKS GRADE


T ID T T E ID E
NAME CITY NAME

42
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

From Requirements: (studentid, courseid is Composite Primarykey)


studentid,courseid studentname
studentid,courseid studentcity
studentid,courseid dob PartialFunctional dependencies.

studentid,courseid coursename
studentid,courseid duration
studentid,courseid marks
studentid,coursedgrade Full Functionaldependencies

After removing partial functional dependencies from above table

STUDENT

STUDENTI STUDENTNAM STUDENTCIT DOB


D E Y
COURSE
COURSEI COURSENAM DURATIO
D E N

RESULT
STUDENTI COURSEI MARKS GRADE
D D
THIRD NORMAL FORM

A relation is said to be in the third normal form if and only if


*it is in Second Normal Form
*No transitive dependency exists between non-key attributes and key attribute
studentid,coursedmarks

marks grade Transitivedependency

studentid,courseid grade

After removing transitive dependency from above table


STUDENT
STUDENTI STUDENTNAM STUDENTCIT DOB
D E Y
COURSE
COURSEI COURSENAM DURATIO
D E N
MARKS
43
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

MARKID RANGE1 RANGE2


RESULT
STUDENTI COURSEI MARKID
D D
Result:

Thus the SQL / PLSQL commands have been executed and the output was verified
successfully.

44
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

Ex.No.9 Database Connectivity with Front End Tools


AIM:
To design and implement a database application for library management system using Netbeans
and mysql.(Login Module)

PROBLEM STATEMENT:
The case study of library management system gives the complete information about the
library. We can enter the record of new book and retrieve the details of books available in the
library. We can issue the books to the students and maintain their records and also check how
many books are issued and stock available in the library. We can also search the books available
in the library.

Sample Code

Database:

import java.sql.Connection;
import java.sql.DriverManager;

public class DB {
public static Connection getConnection(){
Connection con=null;
try{
Class.forName("com.mysql.jdbc.Driver");

con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","","");
}catch(Exception e){System.out.println(e);}
return con;
}

Login:

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import java.awt.Font;
import java.awt.Color;

45
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JPasswordField;

public class AdminLogin extends JFrame {


static AdminLogin frame;
private JPanelcontentPane;
private JTextFieldtextField;
private JPasswordFieldpasswordField;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new AdminLogin();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the frame.
*/
public AdminLogin() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);

JLabellblAdminLoginForm = new JLabel("Admin Login Form");


lblAdminLoginForm.setForeground(Color.GRAY);
lblAdminLoginForm.setFont(new Font("Tahoma", Font.PLAIN, 18));

JLabellblEnterName = new JLabel("Enter Name:");

JLabellblEnterPassword = new JLabel("Enter Password:");

46
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

textField = new JTextField();


textField.setColumns(10);

JButtonbtnLogin = new JButton("Login");


btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name=textField.getText();
String password=String.valueOf(passwordField.getPassword());
if(name.equals("admin")&&password.equals("admin123")){
AdminSuccess.main(new String[]{});
frame.dispose();
}else{
JOptionPane.showMessageDialog(AdminLogin.this, "Sorry,
Username or Password Error","Login Error!", JOptionPane.ERROR_MESSAGE);
textField.setText("");
passwordField.setText("");
}
}
});

passwordField = new JPasswordField();


GroupLayoutgl_contentPane = new GroupLayout(contentPane);
gl_contentPane.setHorizontalGroup(
gl_contentPane.createParallelGroup(Alignment.TRAILING)
.addGroup(gl_contentPane.createSequentialGroup()

.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)

.addGroup(gl_contentPane.createSequentialGroup()
.addGap(124)
.addComponent(lblAdminLoginForm))

.addGroup(gl_contentPane.createSequentialGroup()
.addGap(19)

.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
.addComponent(lblEnterName)
.addComponent(lblEnterPassword))
.addGap(47)

.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING, false)
.addComponent(passwordField)
.addComponent(textField,
GroupLayout.DEFAULT_SIZE, 172, Short.MAX_VALUE))))
.addContainerGap(107, Short.MAX_VALUE))
.addGroup(gl_contentPane.createSequentialGroup()

47
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

.addContainerGap(187, Short.MAX_VALUE)
.addComponent(btnLogin,
GroupLayout.PREFERRED_SIZE, 86, GroupLayout.PREFERRED_SIZE)
.addGap(151))
);
gl_contentPane.setVerticalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addComponent(lblAdminLoginForm)
.addGap(26)

.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
.addComponent(lblEnterName)
.addComponent(textField,
GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
GroupLayout.PREFERRED_SIZE))
.addGap(28)

.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
.addComponent(lblEnterPassword)
.addComponent(passwordField,
GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
GroupLayout.PREFERRED_SIZE))
.addGap(18)
.addComponent(btnLogin,
GroupLayout.PREFERRED_SIZE, 37, GroupLayout.PREFERRED_SIZE)
.addContainerGap(80, Short.MAX_VALUE))
);
contentPane.setLayout(gl_contentPane);
}
}

Output:

Database:

Login:

48
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

Result:

Thus, The SQL / PLSQL commandsand the java GUI application have been executedand
the output was verified successfully.

49
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

Exp.No: 10 Login System


AIM:
To design and implement a Login System using JDK, JDBC, Eclipse IDE and mysql.

PROJECT CODE:

Database Setup
create database swing_demo;

CREATE TABLE student

( id int NOT NULL,

name varchar(250) NOT NULL,

password varchar(250)

);

INSERT INTO student (id, name, password)

VALUES (1, 'WARSHINI R', '12345');

User Login Form


package com.javaguides.javaswing.login;

import java.awt.Color;

import java.awt.EventQueue;

import java.awt.Font;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

50
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.JPasswordField;

import javax.swing.JTextField;

import javax.swing.border.EmptyBorder;

public class UserLogin extends JFrame {

private static final long serialVersionUID = 1L;

private JTextField textField;

private JPasswordField passwordField;

private JButton btnNewButton;

private JLabel label;

private JPanel contentPane;

/**

* Launch the application.

*/

public static void main(String[] args) {

EventQueue.invokeLater(new Runnable() {

public void run() {

try {

UserLogin frame = new UserLogin();

frame.setVisible(true);

} catch (Exception e) {

51
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

e.printStackTrace();

});

/**

* Create the frame.

*/

public UserLogin() {

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setBounds(450, 190, 1014, 597);

setResizable(false);

contentPane = new JPanel();

contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));

setContentPane(contentPane);

contentPane.setLayout(null);

JLabel lblNewLabel = new JLabel("Login");

lblNewLabel.setForeground(Color.BLACK);

lblNewLabel.setFont(new Font("Times New Roman", Font.PLAIN, 46));

lblNewLabel.setBounds(423, 13, 273, 93);

contentPane.add(lblNewLabel);

textField = new JTextField();

textField.setFont(new Font("Tahoma", Font.PLAIN, 32));

textField.setBounds(481, 170, 281, 68);

contentPane.add(textField);

52
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

textField.setColumns(10);

passwordField = new JPasswordField();

passwordField.setFont(new Font("Tahoma", Font.PLAIN, 32));

passwordField.setBounds(481, 286, 281, 68);

contentPane.add(passwordField);

JLabel lblUsername = new JLabel("Username");

lblUsername.setBackground(Color.BLACK);

lblUsername.setForeground(Color.BLACK);

lblUsername.setFont(new Font("Tahoma", Font.PLAIN, 31));

lblUsername.setBounds(250, 166, 193, 52);

contentPane.add(lblUsername);

JLabel lblPassword = new JLabel("Password");

lblPassword.setForeground(Color.BLACK);

lblPassword.setBackground(Color.CYAN);

lblPassword.setFont(new Font("Tahoma", Font.PLAIN, 31));

lblPassword.setBounds(250, 286, 193, 52);

contentPane.add(lblPassword);

btnNewButton = new JButton("Login");

btnNewButton.setFont(new Font("Tahoma", Font.PLAIN, 26));

btnNewButton.setBounds(545, 392, 162, 73);

btnNewButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

String userName = textField.getText();

53
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

String password = passwordField.getText();

try {

Connection connection = (Connection)


DriverManager.getConnection("jdbc:mysql://localhost:3306/swing_demo",

"root", "root");

PreparedStatement st = (PreparedStatement) connection

.prepareStatement("Select name, password from student where name=? and


password=?");

st.setString(1, userName);

st.setString(2, password);

ResultSet rs = st.executeQuery();

if (rs.next()) {

dispose();

UserHome ah = new UserHome(userName);

ah.setTitle("Welcome");

ah.setVisible(true);

JOptionPane.showMessageDialog(btnNewButton, "You have successfully logged in");

} else {

JOptionPane.showMessageDialog(btnNewButton, "Wrong Username & Password");

} catch (SQLException sqlException) {

sqlException.printStackTrace();

});

54
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

contentPane.add(btnNewButton);

label = new JLabel("");

label.setBounds(0, 0, 1008, 562);

contentPane.add(label);

}}

User Home Page

private static final long serialVersionUID = 1 L;

private JPanel contentPane; package com.javaguides.javaswing.login;

import java.awt.Color;

import java.awt.EventQueue;

import java.awt.Font;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.UIManager;

import javax.swing.border.EmptyBorder;

public class UserHome extends JFrame {

55
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

/**

* Launch the application.

*/

public static void main(String[] args) {

EventQueue.invokeLater(new Runnable() {

public void run() {

try {

UserHome frame = new UserHome();

frame.setVisible(true);

} catch (Exception e) {

e.printStackTrace();

});

public UserHome() {

/**

* Create the frame.

*/

public UserHome(String userSes) {

56
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setBounds(450, 190, 1014, 597);

setResizable(false);

contentPane = new JPanel();

contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));

setContentPane(contentPane);

contentPane.setLayout(null);

JButton btnNewButton = new JButton("Logout");

btnNewButton.setForeground(new Color(0, 0, 0));

btnNewButton.setBackground(UIManager.getColor("Button.disabledForeground"));

btnNewButton.setFont(new Font("Tahoma", Font.PLAIN, 39));

btnNewButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

int a = JOptionPane.showConfirmDialog(btnNewButton, "Are you sure?");

// JOptionPane.setRootFrame(null);

if (a == JOptionPane.YES_OPTION) {

dispose();

UserLogin obj = new UserLogin();

obj.setTitle("Student-Login");

obj.setVisible(true);

dispose();

UserLogin obj = new UserLogin();

obj.setTitle("Student-Login");

obj.setVisible(true);

57
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

});

btnNewButton.setBounds(247, 118, 491, 114);

contentPane.add(btnNewButton);

JButton button = new JButton("Change-password\r\n");

button.setBackground(UIManager.getColor("Button.disabledForeground"));

button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

ChangePassword bo = new ChangePassword(userSes);

bo.setTitle("Change Password");

bo.setVisible(true);

});

button.setFont(new Font("Tahoma", Font.PLAIN, 35));

button.setBounds(247, 320, 491, 114);

contentPane.add(button);

Change Password Form


package com.javaguides.javaswing.login;

import java.awt.Color;

import java.awt.EventQueue;

import java.awt.Font;

58
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.SQLException;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.JTextField;

import javax.swing.border.EmptyBorder;

public class ChangePassword extends JFrame {

private static final long serialVersionUID = 1L;

private JPanel contentPane;

private JTextField textField;

private JLabel lblEnterNewPassword;

/**

* Launch the application.

*/

public static void main(String[] args) {

EventQueue.invokeLater(new Runnable() {

public void run() {

59
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

try {

} catch (Exception e) {

e.printStackTrace();

});

/**

* Create the frame.

*/

public ChangePassword(String name) {

setBounds(450, 360, 1024, 234);

setResizable(false);

contentPane = new JPanel();

contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));

setContentPane(contentPane);

contentPane.setLayout(null);

textField = new JTextField();

textField.setFont(new Font("Tahoma", Font.PLAIN, 34));

textField.setBounds(373, 35, 609, 67);

contentPane.add(textField);

textField.setColumns(10);

JButton btnSearch = new JButton("Enter");

60
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

btnSearch.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

String pstr = textField.getText();

try {

System.out.println("update password name " + name);

System.out.println("update password");

Connection con = (Connection)


DriverManager.getConnection("jdbc:mysql://localhost:3306/swing_demo",

"root", "root");

PreparedStatement st = (PreparedStatement) con

.prepareStatement("Update student set password=? where name=?");

st.setString(1, pstr);

st.setString(2, name);

st.executeUpdate();

JOptionPane.showMessageDialog(btnSearch, "Password has been successfully changed");

} catch (SQLException sqlException) {

sqlException.printStackTrace();

});

btnSearch.setFont(new Font("Tahoma", Font.PLAIN, 29));

btnSearch.setBackground(new Color(240, 240, 240));

61
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

btnSearch.setBounds(438, 127, 170, 59);

contentPane.add(btnSearch);

lblEnterNewPassword = new JLabel("Enter New Password :");

lblEnterNewPassword.setFont(new Font("Tahoma", Font.PLAIN, 30));

lblEnterNewPassword.setBounds(45, 37, 326, 67);

contentPane.add(lblEnterNewPassword);

OUTPUT:

62
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

63
CS8481 DBMSLAB Department of CSE Reg. No.: 312419104055

RESULT:

Thus the Login system is programmed, executed and the DB is connected.

64

You might also like