Dbms Lab
Dbms Lab
DBMS lab
REGULATION – 2021
LIST OF EXPERIMENTS
2
DatabaseQuerying – Simplequeries, Nested queries, Sub queries and Joins
3
Creation of Views, Sequences and Synonyms
4
IMPLEMENTATION OF CURSORS
5B
Creation of Procedures
6
Creation of database triggers
7
PL/SQL block that handles all types of exceptions.
8
Database Design using ER modeling, normalization and Implementation
9
RAILWAY RESERVATION SYSTEM
Ex.No:1
Data Definition Commands, Data Manipulation Commands for inserting, deleting, updating
and retrieving Tables and Transaction Control statements
AIM:
To create the database using Data Definition Language(DDL) Commands and to perform
Insert, Delete, Modify, Alter, Update and View the records using Data Manipulation Language
(DML) Commands and to control the tables using Transaction Control Statements.
CREATE
CREATE command is used to create tables in database.
Syntax
CREATE TABLE <table name> (column1 datatype1,…, column datatypen);
RENAME
RENAME command is used to rename the tables.
Syntax
Rename <old table name> to <new table name>;
ALTER
The structure of a table can be changed using this command. Using this command we can do the
following.
i. Add a new column.
ii. Change the width of a data type
iii. Change the data type of a column
While altering the columns the values of the particular column should be empty.
Syntax
ALTER TABLE <table name> MODIFY (column datatype,…);
ALTER TABLE <table name> ADD (column datatype,…);
TRUNCATE
It is used to remove all the records in the table including the space allocated for the table.
But the structure of the table is retained.
TRUNCATE TABLE <table name>;
DROP
This command is used to remove a table from the database.
Syntax
DROP TABLE <table name>;
Output
CREATE
SQL> create table employee (Employee_namevarchar(10), employee_no number(8), dept_name
varchar(10),dept_no number (5),date_of_join date);
Table created.
Table created.
DESC
SQL>desc employee1;
Name Null? Type
EMPLOYEE_NAME VARCHAR2(10)
EMPLOYEE_NO NOT NULL NUMBER(8)
DEPT_NAME VARCHAR2(10)
DEPT_NO NUMBER(5)
DATE_OF_JOIN DATE
RENAME
SQL> Rename employee to employee2;
Table renamed.
ALTER
SQL> alter table employee1 add ( salary number);
SQL> alter table employee1 modify ( salaryvarchar(10));
Table altered.
Table altered.
TRUNCATE
SQL> truncate table employee1;
Table truncated.
DROP
SQL> drop table employee1;
Table dropped.
The DML commands in the SQL are INSERT, UPDATE, DELETE, SELECT.
INSERT
It is used to insert the values into the table.
Syntax
INSERT INTO <table name> VALUES (value1, value2…);
SQL> INSERT INTO employee1 VALUES(‘&Employee_name’, ’&employee_no’,
‘&dept_name’, ‘&dept_no’,’&date_of_join’);
Using this we can insert ‘N’ no. of rows.
UPDATE
The Update command is used to update (changing values in one or two columns of a row) rows in a
table. Specific rows can also be updated based on some condition.
If the WHERE clause is omitted, then the changes take place in all rows of the table.
Syntax
UPDATE <table_name> SET column1=expression,column2=expression… WHERE
<search_condition>;
DELETE
The delete command is used to delete rows from a table.
Syntax
DELETE FROM<table_name> [WHERE <search_condition>];
Downloaded by Shanmathi Balamurugan (shanmathi0905@gmail.com)
lOMoARcPSD|47775205
SELECT
The Select command is used to retrieve the stored data from a table.
Syntax
SELECT * FROM <table_name>;
OUTPUT:
SQL> create table employee (Employee_namevarchar(10), employee_no number(8), dept_name
varchar(10),dept_no number (5),date_of_join date);
Table created.
INSERT
SQL>insert into employee1 values ('Vijay',345,'CSE',21,'21-jun-2006');
1 row created.
UPDATE
SQL> update employee1 set employee_no=300 where dept_no=67;
1 row updated.
DELETE
SQL> delete from employee1 where employee_no>344;
SQL> delete from employee1 where employee_no =124;
SELECT
SQL> select * from employee1;
It selects all the columns from the table.
SAVE POINT
This command is used to identify a point in a transaction in which it can be restored using Roll
back command.
ROLLBACK
It is used to restore database to original since last commit.
SQL> rollback;
Rollback complete.
SQL> roll back <savepoint Name>
Rollback complete.
SQL> commit;
Commit complete.
SQL> rollback;
Rollback complete.
RESULT
Thus the Database creation using Data Definition Language(DDL) commands, the Insert, Delete,
Modify, Alter, Update and View the records using Data Manipulation Language (DML)
Commands and to control tables using Transaction Control statement was executed successfully.
DESCRIPTION:
JOIN OPERATIONS
INNER JOIN/ NATURAL JOIN/ JOIN: It is a binary operation that allows us to combine
certain selections and a Cartesian product into one operation.
OUTER JOIN: It is an extension of join operation to deal with missing information.
Left Outer Join: It takes tuples in the left relation that did not match with any tuple in
the right relation, pads the tuples with null values for all other attributes from the right
relation and adds them to the result of the natural join.
Right Outer Join: It takes tuples in the right relation that did not match with any tuple
in the left relation, pads the tuples with null values for all other attributes from the left
relation and adds them to the result of the natural join.
Full
tuplesOuter
withJoin:
null Itvalues
combines tuples
for the from attributes
missing both the left
andand thetoright
hem the relation
result ofand
thepads the
natural
join.
CREATION OF TABLE
SQL>create table stud (sname varchar2(30), sid varchar2(10), sage number(10), sarea varchar2(20),
sdept varchar2(20));
Table created.
ARITHMETIC OPERATION
ashwin 201
bhavesh 202
pruthvik 203
charith 204
ashwin 19
bhavesh 18
BETWEEN OPERATOR
SQL> select sname,sarea, sid from studs where sid between 102 and 104;
SNAME SAREA SID
ashwin annanagar
bhavesh nungambakkam
pruthvik Annanagar
LOGICAL AND OPERATOR
SQL> select sname ,sid from studs where sid>102 and sarea='annanagar';
SNAME SID
pruthvik 103
LOGICAL OR OPERATOR
SQL> select sname ,sid from studs where sid>102 or sarea='annanagar';
SNAME SID
ashwin 101
pruthvik 103
charith 104
SPOCKET
750
500
250
100
AGGREGATE FUNCTIONS
400
100
4
SQL> select max(spocket) result from studs;
750
SQL> select sum(spocket) result from studs;
1600
Table created.
1 row created.
1 row created.
1 row created.
10
Downloaded by Shanmathi Balamurugan (shanmathi0905@gmail.com)
lOMoARcPSD|47775205
Table created.
1 row created.
1 row created.
1. Equijoin:
A join which contains an equal to ‘=’ operator in this joins condition
Using Clause:
SQL> select eno,ename,job,dname,loc from emp2 e join dept d using(dno);
On Clause:
SQL> select eno,ename,job,dname,loc from emp2 e join dept d on(e.dno=d.dno);
ENO ENAMEJOB DNAMELOC
11
Downloaded by Shanmathi Balamurugan (shanmathi0905@gmail.com)
lOMoARcPSD|47775205
3. Self Join:
Joining the table itself is called self join.
SQL> select e1.eno,e2.ename,e1.job,e2.dno from emp2 e1,emp2 e2 where
e1.eno=e2.mgr;
ENO ENAME JOB DNO
4. Natural Join:
It compares all the common columns.
SQL> select eno,ename,job,dname,loc from emp2 natural join dept;
ENO ENAMEJOB DNAMELOC
5. Cross Join:
This will give the cross product.
SQL> select eno,ename,job,dname,loc from emp2 cross join dept;
ENO ENAME JOB DNAME LOC
12 rows selected.
6. Outer Join:
It gives the non-matching records along with matching records.
Left Outer Join:
This will display the all matching records and the records which are in left hand side table those
that are in right hand side table.
SQL> select eno,ename,job,dname,loc from emp2 e left outer join dept d
on(e.dno= d.dno);
(OR)
SQL> select eno,ename,job,dname,loc from emp2 e,dept d where e.dno=d.dno(+);
ENO ENAMEJOB DNAMELOC
SQL> select eno,ename,job,dname,loc from emp2 e right outer join dept d on(e.dno =d.dno);
(OR)
SQL> select eno,ename,job,dname,loc from emp2 e,dept d where e.dno(+)=d.dno;
RESULT
Thus the relationship between databases has been implemented using join operation.
DESCRIPTION:
Views
Sequences
Oracle provides the capability to generate sequences of unique numbers, and they are
called sequences.
Just like tables, views and synonyms, a sequence is a type of database object.
Sequences are used to generate unique, sequential integer values that are used as primary
key values in database tables.
The sequence of numbers can be generated in either ascending or descending order.
Synonyms
A synonym is an alias, that is, a form of shorthand used to simplify the task of
referencing a database object.
There are two categories of synonyms, public and private.
A public synonym can be accessed by any system user.
Private synonyms, on the other hand, belong to the system user that creates them and
reside in that user's schema.
A system user can grant the privilege to use private synonyms that they own to other
system users.
In order to create synonyms, we will need to have the CREATE SYNONYM privilege.
This privilege will be granted to us by the DBA.
We must have the CREATE PUBLIC SYNONYM privilege in order to create public
synonyms.
If we own a synonym, we have the right to drop (delete) the synonym. The DROP
SYNONYM command is quite simple.
DROP SYNONYM synonym_name;
In order to drop a public synonym we must include the PUBLIC keyword in the DROP
SYNONYM command.
In order to drop a public synonym, we must have the DROP PUBLIC SYNONYM
privilege.
DROP PUBLIC SYNONYM synonym_name;
OUTPUT:
TO CREATE THE TABLE ‘FVIEWS’
SQL> create table fviews( name varchar2(20),no number(5), sal number(5), dno number(5));
Table created.
1 row created.
1 row created.
1 row created.
Xxx 1 19000 11
Aaa 2 19000 12
Yyy 3 40000 13
SQL> create view ssview( cusname,id) as select name, no from fviews where dno=12;
View created.
CUSNAME ID
aaa 2
View dropped.
Sequences
Creation of table:
SQL> create table class(name varchar(10),id number(10));
Table created.
SQL> /
Enter value for name: brindha
Enter value for id: 02
old 1: insert into class values('&name',&id)
new 1: insert into class values('brindha',02)
1 row created.
SQL> /
Enter value for name: chinthiya
Enter value for id: 03
old 1: insert into class values('&name',&id)
new 1: insert into class values('chinthiya',03)
1 row created.
SQL> select * from class;
NAME ID
anu 1
brindha 2
chinthiya 3
Create Sequence:
SQL> create sequence s_1
2 start with 4
3 increment by 1
4 maxvalue 100
5 cycle;
Sequence created.
anu 1
brindha 2
chinthiya 3
divya 4
Drop Sequence:
SQL> drop sequence s_1;
Sequence dropped.
Synonym:
SQL> select * from class;
NAME ID
Anu 1
Brindha 2
Chinthiya 3
Divya 4
ezhil 5
fairoz 7
hema 9
7 rows selected.
Create synonym:
SQL> create synonym c1 for class;
Synonym created.
SQL> insert into c1 values('kalai',20);
1 row created.
SQL> select * from class;
NAME ID
anu 1
brindha 2
chinthiya 3
divya 4
ezhil 5
fairoz 7
hema 9
kalai 20
8 rows selected.
anu 1
brindha 2
chinthiya 3
divya 4
Ezhil 5
fairoz 7
hema 9
kalai 20
8 rows selected.
1 row created.
NAME ID
anu 1
brindha 2
chinthiya 3
divya 4
ezhil 5
fairoz 7
hema 9
kalai 20
Manu 21
9 rows selected.
Drop Synonym:
SQL> drop synonym c1;
Synonym dropped.
RESULT:
Thus the creation of Views, Sequences andSynonyms has been executed successfully.
Aim:
To Create Cursor for Electricity Bill Calculation.
Procedure :
Implicit Cursor
Whenever any DML operations occur in the database, an implicit cursor iscreated that holds the
rows affected, in that particular operation. These cursorscannot be named and, hence they cannot be
controlled or referred from another placeof the code. We can refer only to the most recent cursor
through the cursor attributes.
Explicit Cursor
Programmers are allowed to create named context area to execute their DMLoperations to get more
control over it. The explicit cursor should be defined in thedeclaration section of the PL/SQL block,
and it is created for the 'SELECT' statementthat needs to be used in the code.
Syntax
DECLARE
CURSOR <cursor_name> IS <SELECT statement><cursor_variable declaration>
BEGIN
OPEN <cursor_name>;
FETCH <cursor_name> INTO <cursor_variable>;
.
.
CLOSE <cursor_name>;
END;
SQL>createtablebill(namevarchar2(10),addressvarchar2(20),cityvarchar2(20),unitnumber(10));
Tablecreated.
SQL>insertintobillvalues('&name','&addess','&city','&unit');Entervalueforname:yuva
Entervalueforaddess:sriviEntervalueforcity:srivilliputurEntervalueforunit:100
old 1:insertintobillvalues('&name','&addess','&city','&unit')new
1:insertintobillvalues('yuva','srivi','srivilliputur','100')
1rowcreated.
SQL>/
Entervalueforname:nithya
Entervalueforaddess:LakshminagarEntervalueforcity:sivakasi
Entervalueforunit:200
old 1:insertintobillvalues('&name','&addess','&city','&unit')
new 1:insertintobillvalues('nithya','Lakshminagar','sivakasi','200')
1rowcreated.
SQL>/
Entervalueforname:maya
Entervalueforaddess:housingboardEntervalueforcity:sivakasi
Entervalueforunit:300
old 1:insertintobillvalues('&name','&addess','&city','&unit')
new 1:insertintobillvalues('maya','housingboard','sivakasi','300')
1rowcreated.
SQL>/
Entervalueforname:jeeva
Entervalueforaddess:RRRnagarEntervalueforcity:sivaganagaiEntervalueforunit:400
old 1:insertintobillvalues('&name','&addess','&city','&unit')
20
Downloaded by Shanmathi Balamurugan (shanmathi0905@gmail.com)
lOMoARcPSD|47775205
new 1:insertintobillvalues('jeeva','RRRnagar','sivaganagai','400')
1rowcreated.
SQL>select*frombill;
SQL>declare
2 cursorcisselect*frombill;
3 bbill%ROWTYPE;
4 begin
5 openc;
7 Loop
8 fetchcintob;
9 if(c%notfound)then
10 exit;
11 Else
12 if(b.unit<=100)then
13 dbms_output.put_line(b.name||''||b.address||' '||b.city||' '||b.unit||' '||b.unit*1);
14 elsif(b.unit>100andb.unit<=200)then
15 dbms_output.put_line(b.name||' '||b.address||' '||b.city||' '||b.unit||'
'||b.unit*2);
16 elsif(b.unit>200andb.unit<=300)then
17 dbms_output.put_line(b.name||' '||b.address||' '||b.city||' '||b.unit||'
'||b.unit*3);
18 elsif(b.unit>300andb.unit<=400)then
19 dbms_output.put_line(b.name||''||b.address||''||b.city||' '||b.unit||' '||b.unit*4);
20 else
21 dbms_output.put_line(b.name||''||b.address||''||b.city||' '||b.unit||' '||b.unit*5);
21
Downloaded by Shanmathi Balamurugan (shanmathi0905@gmail.com)
lOMoARcPSD|47775205
22 endif;
23 endif;
24 endloop;
25 closec;
26 end;
27 /
PL/SQLproceduresuccessfullycompleted.
RESULT:
AIM
DESCRIPTION
PL/SQL PROGRAMMING
As we want output of PL/SQL Program on screen, before Starting writing anything type (Only)
To write program, use Notepad through Oracle using ED command.
SQL> ED ProName
Type the program Save & Exit.
To Run the program
SQL> @ProName
LOOPING STATEMENTS:-
For executing the set of statements repeatedly we can use loops. The oracle supports number of
looping statements like GOTO, FOR, WHILE & LOOP.
Here is the syntax of these all the types of looping statements.
GOTO STATEMENTS
<<LABEL>>
SET OF STATEMENTS
GOTO LABEL;
FOR LOOP
FOR <VAR> IN [REVERSE] <INI_VALUE>..<END_VALUE>
SET OF STATEMENTS
END LOOP;
WHILE LOOP
WHILE (CONDITION) LOOP
SET OF STATEMENTS
END LOOP;
LOOP STATEMENT
LOOP
SET OF STATEMENTS
IF (CONDITION) THEN
EXIT
SET OF STATEMENTS
END LOOP;
While using LOOP statement, we have take care of EXIT condition, otherwise it may go
into infinite loop.
Hello
2. Insert the record into Sailors table by reading the values from the Keyboard.
SQL> create table sailors(sid number(10),sname varchar(10),rating number(10),age
number(10));
Table created.
SQL> /
Enter value for sid: 03
old 2: sidnumber(10):=&sid;
new 2: sidnumber(10):=03;
Enter value for sname: vani
old 3: snamevarchar(10):='&sname';
new 3: snamevarchar(10):='vani';
Enter value for rating: 02
old 4: rating number(10):=&rating;
new 4: rating number(10):=02;
Enter value for age: 25
old 5: age number(10):=&age;
new 5: age number(10):=25;
2 lavanya 1 25
3 vani 2 25
RESULT
DEFINITION
A procedure or function is a logically grouped set of SQL and PL/SQL statements that perform a
specific task. They are essentially sub-programs. Procedures and functions are made up of,
• Declarative part
• Executable part
ARGUMENT: It is the name of the argument to the procedure. Paranthesis can be omitted if no
arguments are present.
IN: Specifies that a value for the argument must be specified when calling the procedure ie. used to
pass values to a sub-program. This is the default parameter.
OUT: Specifies that the procedure passes a value for this argument back to it’s calling environment after
execution ie. used to return values to a caller of the sub-program.
INOUT: Specifies that a value for the argument must be specified when calling the procedure and that
procedure passes a value for this argument back to it’s calling environment after execution.
RETURN: It is the datatype of the function’s return value because every function must return a value, this
clause is required.
PROCEDURES – SYNTAX
variable declaration;
constant declaration;
begin
exception
SQL> create table ititems(itemid number(3), actualprice number(5), ordid number(4), prodid number(4));
Table created.
1 row created.
1 row created.
1 row created.
Procedure created.
2 begin
6 dbms_output.put_line('price is null');
7 end if;
8 end;
9/
Procedure created.
Procedure created.
SQL> declare
2 a number;
3 b number;
4 begin
5 zzz(101,b);
7 end;
8/
2 begin
3 a:=a+1;
4 end;
5/
Procedure created.
SQL> declare
2 a number:=7;
3 begin
4 itit(a);
5 dbms_output.put_line(‘The updated value is ‘||a);
6 end;
7/
RESULT
The PL/SQL programs were executed and their respective outputs were verified.
FUNCTIONS – SYNTAX
create or replace function <function name> (argument in datatype,……) return datatype {is,as}
variable declaration;
constant declaration;
begin
PL/SQL subprogram body;
exception
exception PL/SQL block;
end;
Table created.
TNO TFARE
1001 550
1002 600
Table created.
Xxx 11 10000
30
Downloaded by Shanmathi Balamurugan (shanmathi0905@gmail.com)
lOMoARcPSD|47775205
Yyy 12 10500
Zzz 13 15500
2 trainfunctionittrain.tfare % type;
3 begin
4 select tfare into trainfunction from ittrain where tno=trainnumber;
5 return(trainfunction);
6 end;
7/
2 total number;
3 begin
4 total:=aaa (1001);
5 dbms_output.put_line('Train fare is Rs. '||total);
6 end;
7/
2 a number:=7;
3 f number(10);
4 begin
5 f:=itfact(a);
6 dbms_output.put_line(‘The factorial of the given number is’||f);
7 end;
8/
The factorial of the given number is 5040
PL/SQL procedure successfully completed.
RESULT
Thus the functions were created, executed and their respective outputs were verified.
30
Downloaded by Shanmathi Balamurugan (shanmathi0905@gmail.com)
lOMoARcPSD|47775205
DEFINITION
A trigger is a statement that is executed automatically by the system as a side effect of
a modification to the database. The parts of a trigger are,
Trigger statement: Specifies the DML statements and fires the trigger body. It also specifies the
table to which the trigger is associated.
Trigger body or trigger action: It is a PL/SQL block that is executed when the
triggering statement is used.
Trigger restriction: Restrictions on the trigger can be achieved
The different uses of triggers are as follows,
• To generate data automatically
• To enforce complex integrity constraints
• To customize complex securing authorizations
• To maintain the replicate table
• To audit data modifications
TYPES OF TRIGGERS
• For each row: It specifies that the trigger fires once per row.
• For each statement: This is the default trigger that is invoked. It specifies that the trigger fires
once per statement.
• :new
• :old
These two variables retain the new and old values of the column updated in the database.
The values in these variables can be used in the database triggers for data manipulation
TRIGGERS - SYNTAX
create or replace trigger triggername [before/after] {DML statements}
exception
end;
SQL> create trigger ittrigg before insert or update or delete on itempls for each row
2 begin
4 end;
6/
Trigger created.
* ERROR
at line 1:
* ERROR
at line 1:
ORA-20010: You cannot do manipulation
ORA-06512: at "STUDENT.ITTRIGG", line 2
ORA-04088: error during execution of trigger 'STUDENT.ITTRIGG'
SQL> update itempls set eid=15 where ename='yyy';
update itempls set eid=15 where ename='yyy'
*
ERROR at line 1:
ORA-20010: You cannot do manipulation
ORA-06512: at "STUDENT.ITTRIGG", line 2
ORA-04088: error during execution of trigger 'STUDENT.ITTRIGG'
Trigger dropped.
TO CREATE A TRIGGER THAT RAISES AN USER DEFINED ERROR MESSAGE AND DOSE
NOT ALLOW UPDATION AND INSERTION
SQL> create trigger ittriggs before insert or update of salary on itempls for each row
2 declare
3 triggsalitempls.salary%type;
4 begin
5 select salary into triggsal from itempls where eid=12;
6 if(:new.salary>triggsal or :new.salary<triggsal) then
7 raise_application_error(-20100,'Salary has not been changed');
8 end if;
9 end;
10 /
Trigger created.
RESULT
Thus the Triggers were created, executed and their respective outputs were verified.
DESCRIPTION:
PL/SQL provides a feature to handle the Exceptions which occur in a PL/SQL Block known
as exception Handling. Using Exception Handling we can test the code and avoid it from
exiting abruptly.
SQL> /
Enter value for n: 21
old 2: N INTEGER:=&N;
new 2: N INTEGER:=21;
THE INPUT IS ODD.....
SQL> DECLARE
2 L_NUM1 NUMBER;
3 L_NUM2 NUMBER;
4 BEGIN
5 L_NUM1 := 10;
6 L_NUM2 := 0;
7 DBMS_OUTPUT.PUT_LINE('RESULT:'||L_NUM1/L_NUM2);
8 EXCEPTION
9 WHEN ZERO_DIVIDE THEN
10 DBMS_OUTPUT.PUT_LINE(SQLCODE);
11 DBMS_OUTPUT.PUT_LINE(SQLERRM);
12 END;
13 /
-1476
Thus the PL/SQL program that handles exception has been implemented and output was verified.
AIM: To Create the Database Design Using ER Modeling, Normalization and Implementation.
NORMALIZATION
DEFINITION
Normalization is the analysis of functional dependencies between attributes/data
items of user views. It reduces a complex user view to a set of small and stable subgroups of the
fields and relations. This process helps to design a logical data model known as conceptual data
model.
1NF states that the domain of an attribute must include only atomic (simple,
indivisible) values and that value of any attribute in a tuple must be a single value from the domain
of that attribute.
Attributes must be atomic:
– they can be chars, ints, strings
– they can’t be
1. _ tuples
2. _ sets
3. _ relations
4. _ composite
5. _ multivalued
E-R DIAGRAM
Epnorm 1
Country
Sno
Snamer City
ALGORITHM:
2. Create a employee table with the following fields eno,ename,eadd,sal and having the
eno as the primary key.
1 row created.
4. Emp table is not in the first normal form since it has a composite attribute.So it has been
normalized to first normal form.
BEFORE NORMALIZATION :
After Normalization:
en11 en12
Eno Enam Sal Eno Ead d
e Functional Dependencies (FDs)
Functional dependency describes the relationship between attributes in a relation.
For example, if A and B are attributes of relation R, and B is functionally dependent on A (denoted
A B), if each value of A is associated with exactly one value of B. (A and B may each consist of
one or more attributes.)
Trivial functional dependency means that the right-hand side is a subset ( not necessarily a proper
subset) of the left- hand side.
A functional dependency XY is partial dependency if A can be removed which does not
affect the dependency i.e. (X-(A))Y holds.
Pname Hours
Eno Ename Pno
Before Normalization
a) create the table en21 with eno,ename from the table epnorm2
Table created.
40
Downloaded by Shanmathi Balamurugan (shanmathi0905@gmail.com)
lOMoARcPSD|47775205
Table created.
Table altered.
Table altered.
e) Create table en23 with eno,pno and hours from the table epnorm2.
Table created.
f) Alter table en23 with a foreign key on eno with references on eno from en21
SQL> alter table en23 add constraint en231 foreign key(eno) references en21(eno);
Table altered.
g) Alter table en23 with foreign key on pno with references on pno from en22
SQL> alter table en23 add constraint en232 foreign key(pno) references en22(pno);
Table altered.
After Normalization
en21 En
o ENAM E
en22
pnPnam
o e
en23
en Pn Hour
o o s
41
Downloaded by Shanmathi Balamurugan (shanmathi0905@gmail.com)
lOMoARcPSD|47775205
Sal
Epname Dno
Eno
Dname
Epnorm3
Table created.
Example record
1 row created.
3. The relation does not satisfy the 3rd normal form since dno is not a primary key. So
normalization is done for the third normal form.
Before Normalization
Empdept
Enenamsadndnam oeloe
Table created.
Table created.
c) Alter the table en31 with the constraint primary key on eno.
Table altered.
Table altered.
e) Alter table en31 with the constraint foreign key on dno with reference from dno
in en32
SQL> alter table en31 add constraint en311 foreign key(dno) references
en32(dno)
Table altered.
After Normalization
en31
En enam Sa dn
o e l o
en32
Dno dname
RESULT:
Thus the study of Database Design Using ER Modeling and Normalization was successfully
implemented
DESCRIPTION:
Railway Reservation System is used to book the train tickets.
It has one form
1. Reservation form
Reservation form:
It allows to book the train ticket by selecting the train id and specifying the travel
date and no. of seats to be booked. The information entered is stored in the database.
DATABASE TABLES
TRAIN TABLE
create table train
(
trainid INT PRIMARY KEY,
travels VARCHAR2(50),
departure VARCHAR2(20),
arrival VARCHAR2(20),
duration INT,
seats int,
fare int
);
TRAINBOOKING TABLE
CODING :
MAIN FORM
package e.ticketing;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
//TODO add your handling code here: this.setVisible(false);
new Reservation().setVisible(true)
}
RESERVATION FORM
package e.ticketing;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
public class Reservation extends javax.swing.JFrame { int ttrainid,fare,avail;
public Reservation() {
initComponents();
private void jrathimeenaActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try
{ Class.forName("oracle.jdbc.OracleDriver");
Connection
conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","heme
sh","123");
String sql="select * from train where trainid=2";
PreparedStatement pst=conn.prepareStatement(sql);
ResultSet rs=pst.executeQuery();
if(rs.next())
{
ttrainid =rs.getInt("trainid");
fare =rs.getInt("fare");
}
String sql1="select * from trainbooking where trainid=2";
PreparedStatement pst1=conn.prepareStatement(sql1);
ResultSet rs1=pst1.executeQuery();
if(rs1.next())
{
avail =rs1.getInt("AVAILABLESEATS");
availseat.setText(String.valueOf(avail));
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
PreparedStatement pst=conn.prepareStatement(sql);
ResultSet rs=pst.executeQuery(); if(rs.next()){
ttrainid =rs.getInt("trainid");
fare =rs.getInt("fare");
}
String sql1="select * from trainbooking where trainid=1";
PreparedStatement pst1=conn.prepareStatement(sql1);
ResultSet rs1=pst1.executeQuery();
if(rs1.next())
{
avail =rs1.getInt("AVAILABLESEATS");
availseat.setText(String.valueOf(avail));
}
}catch (Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
{ Class.forName("oracle.jdbc.OracleDriver");
Connectionconn=
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE",
"hemesh", "123");
String sql="update trainbooking set availableseats=? where trainid=?";
PreparedStatement pst=conn.prepareStatement(sql); //create a statement
pst.setInt(1,avail-noseats); pst.setInt(2,ttrainid);
pst.executeUpdate();
JOptionPane.showMessageDialog(null,"Booking Confirmed");
}
else
{ JOptionPane.showMessageDialog(null,"Sorry Seats not Available");
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
}
RESULT:
Thus the project was successfully created, executed and verified.
SAMPLE CODING:
STOCK ENTRY:
package conn;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.swing.JOptionPane;
import oracle.jdbc.OraclePreparedStatement;
import oracle.jdbc.OracleResultSet;
public class stockentry extends javax.swing.JFrame {
Connection conn=null;
OraclePreparedStatement pst=null;
OracleResultSet rs=null;
PreparedStatement pst=conn.prepareStatement(sql);
pst.setString(1,txt_prodid.getText());
pst.setString(2,txt_prodname.getText());
pst.setString(3,txt_quantity.getText());
pst.setString(4,txt_unitprice.getText());
pst.setString(5,txt_reorder.getText());
pst.execute();
JOptionPane.showMessageDialog(null,"Successfully Inserted");
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
pst1.setInt(3,Integer.parseInt( txt_unitprice.getText()));
pst1.setInt(4, Integer.parseInt(txt_salesqty.getText()));
53
Downloaded by Shanmathi Balamurugan (shanmathi0905@gmail.com)
lOMoARcPSD|47775205
pst1.setString(5,date);
pst1.execute();
JOptionPane.showMessageDialog(null, "Sucessfully Inserted");
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
RESULT
Thus the project was successfully created, executed and verified.