You are on page 1of 56

CS8481 DATABASE MANAGEMENT SYSTEMS LABORATORY

EX.NO:1(a) IMPLEMENTATION OF DDL COMMANDS

AIM:
To create a DDL to perform creation of table, alter, modify and drop column.

DDL COMMANDS

1. The Create Table Command: - it defines each column of the table uniquely. Each column
has minimum of three attributes, a name , data type and size.

Syntax:

Create table <table name> (<col1> <datatype>(<size>),<col2>


<datatype><size>)); Ex:create table emp(empno number(4) primary key, ename
char(10));

2. Modifying the structure of


tables. a) Add new columns

Syntax:

Alter table <tablename> add(<new col><datatype(size),<new col>datatype(size));


Ex:alter table emp add(sal number(7,2));

3. Dropping a column from a table.

Syntax:

Alter table <tablename> drop column <col>;

Ex:alter table emp drop column sal;

4. Modifying existing columns.

Syntax:

Alter table <tablename>


modify(<col><newdatatype>(<newsize>)); Ex:alter table emp
modify(ename varchar2(15));
5. Renaming the tables

Syntax:

Rename <oldtable> to <new table>;

Ex:rename emp to emp1;

6. truncating the tables.

Syntax:

Truncate table <tablename>;

Ex:trunc table emp1;

7. Destroying tables.

Syntax:

Drop table <tablename>;

Ex:drop table emp;

CREATION OF TABLE:

SYNTAX:

create table<tablename>(column1 datatype,column2 datatype...);

EXAMPLE:
SQL>create table std(sno number(5),sname varchar(20),age number(5),sdob date,sm1
number(4,2),sm2 number(4,2),sm3 number(4,4));
Table created.

SQL>insert into std values(101,’AAA’,16,’03-jul-88’,80,90,98);


1 row created.

SQL>insert into std values(102,’BBB’,18,’04-aug-89’,88,98,90);


1 row created.

OUTPUT:

Select * from std;

SNO SNAME AGE SDOB SM1 SM2 SM3

101 AAA 16 03-jul-88 80 90 98

102 BBB 18 04-aug-89 88 98 90


ALTER TABLE WITH ADD:

SQL>create table student(id number(5),name varchar(10),game varchar(20));


Table created.

SQL>insert into student values(1,’mercy’,’cricket’);


1 row created.

SYNTAX:

alter table<tablename>add(col1 datatype,col2 datatype..);

EXAMPLE:

SQL>alter table student add(age number(4));


SQL>insert into student values(2,’sharmi’,’tennis’,19);

OUTPUT:

ALTER: select * from student;

ID NAME GAME

1 Mercy Cricket

ADD: select * from student;

ID NAME GAME AGE

1 Mercy cricket

2 Sharmi Tennis 19

ALTER TABLE WITH MODIFY:

SYNTAX:

Alter table<tablename>modify(col1 datatype,col2 datatype..);

EXAMPLE:

SQL>alter table student modify(id number(6),game varchar(25));

OUTPUT:

MODIFY

desc student;

NAME NULL? TYPE


Id Number(6)

Name Varchar(20)

Game Varchar(25)

Age Number(4)

DROP:

SYNTAX: drop table<tablename>;

EXAMPLE:

SQL>drop table student;

SQL>Table dropped.

TRUNCATE TABLE

SYNTAX: TRUNCATE TABLE <TABLE NAME>;

Example: Truncate table stud;

DESC

Example: desc emp;

Name Null? Type

--------------------------------- --------
EmpNo NOT NULL number(5)

EName VarChar(15)

Job NOT NULL Char(10)

DeptNo NOT NULL number(3)

PHONE_NO number (10)

CONSTRAINTS:

Create table tablename (column_name1 data_ type constraints, column_name2 data_


type constraints …)

Example:

Create table Emp ( EmpNo number(5), EName VarChar(15), Job Char(10) constraint
un unique, DeptNo number(3) CONSTRAINT FKey2 REFERENCES DEPT(DeptNo));
Create table stud (sname varchar2(20) not null, rollno number(10) not null,dob date not null);

DOMAIN INTEGRITY

Example: Create table cust(custid number(6) not null, name char(10));

Alter table cust modify (name not null);

CHECK CONSTRAINT

Example: Create table student (regno number (6), mark number (3) constraint b check
(mark >=0 and mark <=100)); Alter table student add constraint b2 check
(length(regno<=4));

ENTITY INTEGRITY

a) Unique key constraint

Example: Create table cust(custid number(6) constraint unique, name char(10)); Alter table
cust add(constraint c unique(custid));

b) Primary Key Constraint

Example: Create table stud(regno number(6) constraint primary key, name char(20));

Queries:

Q1. Create a table called EMP with the following structure.

Name Type
---------- ----------------------

EMPNO NUMBER(6)

ENAME VARCHAR2(20)

JOB VARCHAR2(10)

DEPTNO NUMBER(3)

SAL NUMBER(7,2)

Allow NULL for all columns except ename and job.

Ans:

SQL> create table emp(empno number(6),ename varchar2(20)not null,job varchar2(10)


not null, deptno number(3),sal number(7,2));
Table created.

Q2: Add a column experience to the emp table.


experience numeric null allowed.

Ans: SQL> alter table emp add(experience number(2));


Table altered.

Q3: Modify the column width of the job field of emp table.

Ans: SQL> alter table emp modify(job varchar2(12));


Table altered.

SQL> alter table emp modify(job


varchar(13)); Table altered.

Q4: Create dept table with the following structure.

Name Type

------------ ---------------------

DEPTNO NUMBER(2)

DNAME VARCHAR2(10)

LOC VARCHAR2(10)

Deptno as the primarykey

Ans:
SQL> create table dept(deptno number(2) primary key,dname
varchar2(10),loc varchar2(10));
Table created.

Q5: create the emp1 table with ename and empno, add constraints to check the empno value
while entering (i.e) empno > 100.

Ans:
SQL> create table emp1(ename varchar2(10),empno number(6) constraint

check(empno>100));

Table created.

Q6: drop a column experience to the emp table.

Ans:

SQL> alter table emp drop column experience; Table altered.

Q7: Truncate the emp table and drop the dept table

Ans: SQL> truncate table emp; Table truncated.

RESULT:
Thus the DDL commands have been executed successfully.
EX.NO:1(b) IMPLEMENTATION OF DML AND DCL COMMANDS

AIM:
To study the various DML commands and implement them on the database.

DML COMMANDS

DML commands are the most frequently used SQL commands and is used to
query and manipulate the existing database objects. Some of the commands are Insert,
Select, Update, Delete.

Insert Command : This is used to add one or more rows to a table. The values are separated
by commas and the data types char and date are enclosed in apostrophes. The values must be
entered in the same order as they are defined.

Select Commands : It is used to retrieve information from the table. It is generally referred
to as querying the table. We can either display all columns in a table or only specify
column from the table.

Update Command :It is used to alter the column values in a table. A single column may
be updated or more than one column could be updated.

Delete command :After inserting row in a table we can also delete them if required. The
delete command consists of a from clause followed by an optional where clause.

Q1: Insert a single record into dept table.


Ans: SQL> insert into dept values (1,'IT','Tholudur');
1 row created.

Q2: Insert more than a record into emp table using a single insert command.
Ans: SQL> insert into emp values(&empno,'&ename','&job',&deptno,&sal);
Enter value for empno: 1
Enter value for ename: Mathi
Enter value for job: AP
Enter value for deptno: 1
Enter value for sal: 10000
old 1: insert into emp values(&empno,'&ename','&job',&deptno,&sal)
new 1: insert into emp values(1,'Mathi','AP',1,10000)

1 row created.

SQL> / Enter value for empno: 2

Enter value for ename: Arjun


Enter value for job: ASP
Enter value for deptno: 2
Enter value for sal: 12000
old 1: insert into emp values(&empno,'&ename','&job',&deptno,&sal)
new 1: insert into emp values(2,'Arjun','ASP',2,12000)
1 row created.

SQL> / Enter value for empno: 3


Enter value for ename: Gugan

Enter value for job: ASP

Enter value for deptno: 1

Enter value for sal: 12000

old 1: insert into emp values(&empno,'&ename','&job',&deptno,&sal)

new 1: insert into emp values(3,'Gugan','ASP',1,12000)

1 row created.

Q3: Update the emp table to set the salary of all employees to Rs15000/- who are working as

ASP

Ans: SQL> select * from emp;

EMPNO ENAME JOB DEPTNO SAL

---------- -------------------- ------------- ---------- ----------

1 Mathi AP 1 10000

2 Arjun ASP 2 12000

3 Gugan ASP 1 12000


SQL> update emp set sal=15000 where job='ASP'; 2 rows updated.

SQL> select * from emp;

EMPNO ENAME JOB DEPTNO SAL

---------- -------------------- ------------- ---------- ----------

1 Mathi AP 1 10000

2 Arjun ASP 2 15000

3 Gugan ASP 1 15000

Q4: Create a pseudo table employee with the same structure as the table emp and insert
rows into the table using select clauses.

Ans: SQL> create table employee as select * from emp;

Table created.

SQL> desc employee;

Name Null? Type

----------------------------------------- -------- ----------------------------

EMPNO NUMBER(6)

ENAME NOT NULL VARCHAR2(20)

JOB NOT NULL VARCHAR2(13)

DEPTNO NUMBER(3)

SAL NUMBER(7,2)
Q5: select employee name, job from the emp table

Ans: SQL> select ename, job from emp;

ENAME JOB

-------------------- -------------

Mathi AP

Arjun ASP

Gugan ASP

Karthik Prof

Akalya AP

suresh lect

6 rows selected.
Q6: Delete only those who are working as lecturer

Ans: SQL> select * from emp;

EMPNO ENAME JOB DEPTNO SAL

---------- -------------------- ------------- ---------- ----------

1 Mathi AP 1 10000

2 Arjun ASP 2 15000

3 Gugan ASP 1 15000

4 Karthik Prof 2 30000

5 Akalya AP 1 10000

6 suresh lect 1 8000

6 rows selected.

SQL> delete from emp where job='lect';

1 row deleted.

SQL> select * from emp;

EMPNO ENAME JOB DEPTNO SAL

- --------- -------------------- ------------- ---------- ----------

1 Mathi AP 1 10000

2 Arjun ASP 2 15000


3 Gugan ASP 1 15000

4 Karthik Prof 2 30000

5 Akalya AP 1 10000

Q7: List the records in the emp table orderby salary in ascending order.

Ans: SQL> select * from emp order by sal;

EMPNO ENAME JOB DEPTNO SAL

---------- -------------------- ------------- ---------- ----------

1 Mathi AP 1 10000

5 Akalya AP 1 10000

2 Arjun ASP 2 15000

3 Gugan ASP 1 15000


4 Karthik Prof 2 30000

Q8: List the records in the emp table orderby salary in descending order.

Ans: SQL> select * from emp order by sal desc;

EMPNO ENAME JOB DEPTNO SAL

---------- -------------------- ------------- ---------- ----------

4 Karthik Prof 2 30000

2 Arjun ASP 2 15000

3 Gugan ASP 1 15000

1 Mathi AP 1 10000

5 Akalya AP 1 10000

Q9: Display only those employees whose deptno is 30.

Solution: Use SELECT FROM WHERE syntax.

Ans: SQL> select * from emp where deptno=1;

EMPNO ENAME JOB DEPTNO SAL

---------- -------------------- ------------- ---------- ----------

1 Mathi AP 1 10000

3 Gugan ASP 1 15000

5 Akalya AP 1 10000
Q10: Display deptno from the table employee avoiding the duplicated values.

Solution:

1. Use SELECT FROM syntax.

2.Select should include distinct clause for the deptno.

Ans: SQL> select distinct deptno from emp;

DEPTNO

----------

2
IMPLEMENTATION OF DATA AND BUILT IN FUNCTIONS IN SQL
CHARACTER/STRING FUNCTION:

SQL> select upper('welcome') from dual;

-----------
WELCOME

SQL> select upper('hai') from dual;


---
HAI

SQL> select lower('HAI') from dual;

LOW

---

hai

SQL> select initcap(‘hello world') from dual;

INITCAP('Hello
--------------
Hello World

SQL> select ltrim(' hai') from dual;


LTR
---
hai

SQL> select rtrim('hai ')from dual;


RTR

---

hai

SQL> select rtrim(' hai ')from dual;

RTRIM('

------
-

hai

SQL> select concat('SRM',' university')from dual;

------------------------

SRM university

SQL> select length('SRM’)from dual;

LENGTH('SRM')
----------------------
12

SQL> select replace('SRM university', 'SRM','Anna')from dual;


----------------
Anna university
SQL> select rpad('hai',3,'*')from dual;

RPAD('
------
hai***

SQL> select lpad('hai',3,'*')from dual;


LPAD('
------
***hai

SQL> select replace('Dany','y','ie')from dual;

REPLACE
-------
Danie

SQL> select translate('cold','ld','ol')from dual;


TRANSL
------
cool
DATE & TIME FUNCTION

SQL> select sysdate from dual;

SYSDATE

---------

07-APR-10

SQL> select round(sysdate)from dual;

ROUND(SYS

---------

07-APR-10

SQL> select add_months(sysdate,3)from dual;

ADD_MONTH

---------

07-JUL-10

SQL> select last_day(sysdate)from dual;

LAST_DAY(

---------

30-APR-10

SQL> select sysdate+20 from dual;

SYSDATE+2

---------

27-APR-10

SQL> select next_day(sysdate,'tuesday')from dual;

NEXT_DAY(

---------

13-APR-10
NUMERIC FUNCTION

SQL> select round(15.6789)from dual;

ROUND(15.6789)

--------------

16

SQL> select ceil(23.20)from dual;

CEIL(23.20)

-----------

24

SQL> select floor(34.56)from dual;

FLOOR(34.56)

------------

34

SQL> select trunc(15.56743)from dual;

TRUNC(15.56743)

---------------

15

SQL> select sign(-345)from dual;

SIGN(-345)

----------

-1

SQL> select abs(-70)from dual;

ABS(-70)

---------

70
MATH FUNCTION:

SQL> select abs(45) from dual;

ABS(45)

---------

45

SQL> select power(10,12) from dual;

POWER(10,12)

------------

1.000E+12

SQL> select mod(11,5) from dual;

MOD(11,5)

---------

SQL> select exp(10) from dual;

EXP(10)

---------

22026.466

SQL> select sqrt(225) from dual;

SQRT(225)

---------

15
DCL COMMANDS

The DCL language is used for controlling the access to the table and hence securing the
database. DCL is used to provide certain privileges to a particular user. Privileges are rights
to be allocated.The privilege commands are namely, Grant and Revoke.The various
privileges that can be granted or revoked are, Select Insert Delete Update References
Execute All.

GRANT COMMAND: It is used to create users and grant access to the database. It requires
database administrator (DBA) privilege, except that a user can change their password. A user
can grant access to their database objects to other users.

REVOKE COMMAND: Using this command , the DBA can revoke the granted database
privileges from the user.

TCL COMMAND

COMMIT: command is used to save the Records.

ROLL BACK: command is used to undo the Records.

SAVE POINT command is used to undo the Records in a particular transaction.

Queries:

Tables Used: Consider the following tables namely “DEPARTMENTS”


and “EMPLOYEES”

Their schemas are as follows , Departments ( dept _no , dept_ name , dept_location );
Employees ( emp_id , emp_name , emp_salary );

Q1: Develop a query to grant all privileges of employees table into departments table

Ans: SQL> Grant all on employees to


departments; Grant succeeded.

Q2: Develop a query to grant some privileges of employees table into departments table

Ans: SQL> Grant select, update , insert on departments to departments with grant
option; Grant succeeded.

Q3: Develop a query to revoke all privileges of employees table from departments table

Ans: SQL> Revoke all on employees from departments; Revoke succeeded.

Q4: Develop a query to revoke some privileges of employees table from departments table

Ans: SQL> Revoke select, update , insert on departments from departments;


Revoke succeeded.
Q5: Write a query to implement the save point

Ans: SQL> SAVEPOINT S1;

Savepoint created.

SQL> select * from emp;

EMPNO ENAME JOB DEPTNO SAL

---------- -------------------- ------------- ---------- ----------

1 Mathi AP 1 10000

2 Arjun ASP 2 15000

3 Gugan ASP 1 15000

4 Karthik Prof 2 30000

SQL> INSERT INTO EMP VALUES(5,'Akalya','AP',1,10000); 1 row


created. SQL> select * from emp;

EMPNO ENAME JOB DEPTNO SAL

---------- -------------------- ------------- ---------- ----------

1 Mathi AP 1 10000

2 Arjun ASP 2 15000

3 Gugan ASP 1 15000

4 Karthik Prof 2 30000

5 Akalya AP 1 10000
Q6: Write a query to implement the rollback

Ans: SQL> rollback s1; SQL> select * from emp;

EMPNO ENAME JOB DEPTNO SAL

---------- -------------------- ------------- ---------- ----------

1 Mathi AP 1 10000

2 Arjun ASP 2 15000

3 Gugan ASP 1 15000

4 Karthik Prof 2 30000


Q6: Write a query to implement the commit

Ans: SQL> COMMIT;

Commit complete.

RESULT

Thus the DML, DCL,TCL commands was performed successfully and executed.
Exp. 2.

Database Querying – Simple queries, Nested queries, Sub queries and Joins

Aim:
To execute and verify the Simple queries, Nested queries, Sub queries and Joins in SQL.

Queries and sub queries:

Table 1:

Create table department ( deptname varchar(20), building varchar (15),


budget number(12,2), primary key(deptname));

Table created.

Insert into department values('ECE','block1',70000);


Insert into department values('CSE','block2',70000);
Insert into department values('EEE','block3',70000);

Table 2:

create table course ( courseid varchar(8) primary key, title varchar(50), deptname
varchar(20), credits number(2), foreign key (deptname) references department) ;

Table created.

Insert into course values('cs101','python','CSE',4);


Insert into course values('cs102','java','CSE',4);
Insert into course values('ec102','Electronics circuits','ECE',3);
Insert into course values('ec202','Microprocessor','ECE',3);

Table 3:

create table instructor (ID varchar(5), name varchar(20) not null,


deptname varchar(20), salary number(8,2), primary key (ID),
foreign key (deptname) references department);

insert into instructor values ('1002', 'Sumanth', 'ECE', 66000);


insert into instructor values ('1001', 'Sumitha', 'CSE', 56000);
insert into instructor values ('1007', 'Malar', 'CSE', 96000);
insert into instructor values ('1004', 'Mani', 'ECE', 36000);

Table 4:

Create table section ( courseid varchar(8), secid varchar(8), semester varchar(6), year
number(4), building varchar(15) , roomnumner varchar(7), timeslot varchar(4),
primary key (courseid, secid, semester, year), foreign key (courseid) references
course);

Insert into section values('cs101','A','odd',2017,'block2','111','11');


Insert into section values('cs101','A','even',2018,'block2','222','5');
Insert into section values('cs102','A','even',2016,'block2','77','8');
Insert into section values('ec202','A','even',2016,'block1','47','8');
Insert into section values('ec202','B','odd',2017,'block1','47','8');
Insert into section values('ec202','C','even',2018,'block1','47','8');

Table 5:

create table teaches (ID varchar(5), courseid varchar(8), secid varchar(8),


semester varchar(6), year number(4), primary key (ID, courseid, secid, semester,
year), foreign key (ID) references instructor, foreign key (courseid, secid, semester,
year) references section );

Insert into teaches values('1001', 'cs101','A','odd',2017);


Insert into teaches values('1007', 'cs102','A','even',2016);
Insert into teaches values('1002', 'ec202','A','even',2016);

Questions:

 Find the names of all departments with instructor, and remove duplicates
select distinct dept_name from instructor;
 To find all instructors in CSE with salary > 80000
select name from instructor where dept_name = ‘Comp. Sci.' and salary >
80000;
 Find the Cartesian product instructor X teaches
select *from instructor, teaches;
 Find the course ID, semester, year and title of each course offered by the Comp.
Sci. department

select section.courseid, semester, year, title from section, course where


section.courseid = course.courseid and deptname = ‘CSE';
 List the names of instructors along with the course ID of the courses that they
taught.

select name, courseid from instructor, teaches where instructor.ID =


teaches.ID;
select name, courseid from instructor natural join teaches;

 Find the names of all instructors who have a higher salary than some
instructor in ‘Comp. Sci’.
select distinct T. name from instructor as T, instructor as S where
T.salary > S.salary and S.deptname = ‘CSE’
o Find the names of all instructors whose name includes the substring
“dar”.
select name from instructor where name like '%dar%';

 List in alphabetic order the names of all instructors


select distinct name from instructor order by name;
 Find the names of all instructors with salary between
$90,000 and $100,000 (that is,  $90,000 and  $100,000)
select name from instructor where salary between 90000 and 100000;

nested quries:

Q1: Display all employee names and salary whose salary is greater than minimum salary
of the company and job title starts with ‗M‘.
Solution:

1. Use select from clause.

2. Use like operator to match job and in select clause to get the result.

Ans: SQL> select ename,sal from emp where sal>(select min(sal) from emp where job
like 'A%');

ENAME SAL
-------------------- ----------
Arjun 12000
Gugan 20000
Karthik 15000

Q2: Issue a query to find all the employees who work in the same job as Arjun.
Ans: SQL> select * from emp;
EMPNO ENAME JOB DEPTNO SAL
---------- -------------------- ---------- ---------- ----------
1 Mathi AP 1 10000
2 Arjun ASP 2 12000
3 Gugan ASP 2 20000
4 Karthik AP 1 15000

SQL> select ename from emp where job=(select job from emp where
ename='Arjun');
ENAME
--------------
Arjun

Gugan
Set Operations:
 Find courses that ran in Fall 2009 or in Spring 2010
(select course_id from section where sem = ‘Fall’ and year = 2009) union (select
course_id from section where sem = ‘Spring’ and year = 2010)

 Find courses that ran in Fall 2009 and in Spring 2010


(select course_id from section where sem = ‘Fall’ and year = 2009) intersect (select
course_id from section where sem = ‘Spring’ and year = 2010)

 Find courses that ran in Fall 2009 but not in Spring 2010
(select course_id from section where sem = ‘Fall’ and year = 2009) except (select
course_id from section where sem = ‘Spring’ and year = 2010)

AGGREGATE FUNCTIONS:
 Find the average salary of instructors in the Computer Science department
select avg (salary) from instructor where dept_name= ’Comp.Sci.’;
 Find the total number of instructors who teach a course in the Spring 2010
semester
 select count (distinct ID) from teaches where
semester = ’Spring’ and year = 2010
Find the number of tuples in the course relation
o select count (*) from course;
o Find the names and average salaries of all departments whose average
salary is greater than 42000
select dept_name, avg (salary) from instructor group by dept_name having
avg (salary) > 42000;

NESTED SUBQUERIES:
 Find courses offered in Fall 2009 and in Spring 2010
 select distinct course_id from section where semester =
’Fall’ and year= 2009 and course_id in (select course_id
from section where semester = ’Spring’ and year= 2010);
Find courses offered in Fall 2009 but not in Spring 2010
 select distinct course_id from section where semester = ’Fall’ and year=
2009 and course_id not in (select course_id from section where semester =
’Spring’ and year= 2010);

JOINED RELATIONS
Join operations – Example
 Relation course

 Relation prereq
Outer Join
 An extension of the join operation that avoids loss of information.
 Computes the join and then adds tuples form one relation that does not match
tuples in the other relation to the result of the join.
 Uses null values.
Left Join:
SELECT * FROM course left join prereq on course.course_id=prereq.course_id;

Right Join:
Select *from course right join prereq on course.course_id=prereq.course_id;

Full join:
Select *from course full join prereq on course.course_id=prereq.course_id:
RESULT:

Thus the Simple queries, Nested queries, Sub queries and Joins in SQL are executed
successfully.

Exp.3
Views, Synonyms, Sequence

AIM:

To create the view, Synonyms, Sequence and execute various operations.

View:
Database views are created using the CREATE VIEW statement. Views can be
created from a single table, multiple tables, or another view. To create a view, a user must
have the appropriate system privilege according to the specific implementation.

SQL> CREATE TABLE EMPLOYEE (

EMPLOYEE_NAMEVARCHAR2(10),
EMPLOYEE_NO NUMBER(8),
DEPT_NAME VARCHAR2(10),

DEPT_NO NUMBER (5),


DATE_OF_JOIN DATE
);

Table created.
CREATE VIEW

SUNTAX FOR CREATION OF VIEW

CREATE [OR REPLACE] [FORCE ] VIEW viewname


[(column-name, column-name)] AS Query [with check
option];
Include all not null attribute.

CREATION OF VIEW

SQL> CREATE VIEW EMPVIEW AS SELECT EMPLOYEE_NAME,

EMPLOYEE_NO,
DEPT_NAME,
DEPT_NO,
DATE_OF_JOIN FROM EMPLOYEE;
View Created.

DISPLAY VIEW:

SQL> SELECT * FROM EMPVIEW;


DEPT_N
EMPLOYEE_N EMPLOYEE_NO DEPT_NAME O
--------------
--------------------- ----------------------- ------------------- -
RAVI 124 ECE 89
VIJAY 345 CSE 21
RAJ 98 IT 22
GIRI 100 CSE 67

SQL> INSERT INTO EMPVIEW VALUES ('SRI', 120,'CSE', 67);

1 ROW CREATED.

SQL>DROP VIEW EMPVIEW;


view dropped

SQL> CREATE OR REPLACE VIEW EMP_TOTSAL AS


SELECT EMPNO "EID", ENAME "NAME", SALARY "SAL"
FROM EMPL;
JOIN VIEW:

EXAMPLE-5:

SQL> CREATE OR REPLACE VIEW DEPT_EMP_VIEW AS SELECT A.EMPNO,

A.ENAME,

A.DEPTNO,

B.DNAME,

B.LOC

FROM EMPL A, DEPMT


B

WHERE
A.DEPTNO=B.DEPTNO;
Synonyms
A synonym is an alias for any table, view, materialized view, sequence,
procedure, function, package, type, Java class schema object, user-defined object type,
or another synonym. Because a synonym is simply an alias, it requires no storage other
than its definition in the data dictionary.
Synonyms are often used for security and convenience. For example, they can do the following:
Mask the name and owner of an object

Provide location transparency for remote objects of a distributed


You can create both public and private synonyms. A public synonym is owned by the
special user group named PUBLIC and every user in a database can access it. A private
synonym is in the schema of a specific user who has control over its availability to others.

CREATE THE TABLE

SQL> CREATE TABLE student_table(Reg_No number(5),NAME varchar2(5),MARK


number(3)); Table created.
CREATE THE SYNONYM FROM TABLE

SQL> CREATE SYNONYM STUDENT_SYNONYM FOR STUDENT_TABLE;

Synonym created.
DISPLAY THE VALUES OF TABLE BY USING THE SYSNONYM

SQL> select * from STUDENT_SYNONYM;

REG_NO NAME MARK


------------ ------------- ----------
10001 ram 85
10002 sam 75
10003 samu 95

INSERT THE VALUES TO THE SYNONYM

SQL> insert into student_SYNONYM values(10006,'RAJA',80);

1 row created.
Sequence
The sequence generator provides a sequential series of numbers. The sequence
generator is especially useful in multiuser environments for generating unique
sequential numbers without the overhead of disk I/O or transaction locking
Sequence numbers are integers of up to 38 digits defined in the database. A
sequence definition indicates general information, such as the following:
SYNTAX:
SQL>CREATE SEQUENCE sequence_name

[START WITH start_num]

[INCREMENT BY increment_num]
[ { MAXVALUE maximum_num | NOMAXVALUE } ] [

{ MINVALUE minimum_num | NOMINVALUE } ]

[ { CYCLE | NOCYCLE } ]

[ { CACHE cache_num | NOCACHE } ] [

{ ORDER | NOORDER } ];

NOCYCLE means the sequence cannot generate any more integers after reaching its
maximum or minimum value. NOCYCLE is the default.
NOMAXVALUE specifies the maximum is 1027 for an ascending sequence or –1 for a
descending sequence. NOMAXVALUE is the default.
NOMINVALUE specifies the minimum is 1 for an ascending sequence or –1026 for a
descending sequence. NOMINVALUE is the default.

If you omit CACHE and NOCACHE, the database caches 20 sequence numbers by
default.

ORDER guarantees the integers are generated in the order of the request. You typically
use ORDER when using Real Application Clusters, which are set up and managed by
database administrators.

NOORDER doesn’t guarantee the integers are generated in the order of the
request.

NOORDER is the default.

Example: 1

Command:

SQL> CREATE SEQUENCE seq1


INCREMENT BY 1
START with 1
MAXVALUE 5
MINVALUE 0;

Sequence created.

TO DISPLAY THE VALUES OF SEQUENCES

After creating sequence use nextval as nextval is used to


generate sequence values SQL> select seq1.nextval from dual;

NEXTVAL
----------
1
SQL> select seq1.nextval from dual;

NEXTVAL
----------

SQL> select seq1.nextval from dual;

NEXTVAL
----------
3

SQL> select seq1.currval from dual;

CURRVAL
----------
3
TO ALTER THE SEQUENCES

alter SEQUENCE seq1 maxvalue 25 INCREMENT BY cycle cache 2 ;


create table test1(a number primary key);

TO INSERT THE VALUES FROM SEQUENCES TO TABLE:

insert into test1 values(seq1.nextval)

TO DROP SEQUENCES

drop sequence sequenceNAme


Result :

Thus the view, Synonyms, Sequenceeen created and various operations are performed
and output is verified..

EXP.4

PROCEDURES AND FUNCTIONS


Aim :
To create PL/SQL procedures and functions.

Procedures:
At the schema level, subprogram is a standalone subprogram. It is created with the CREATE
PROCEDURE or the CREATE FUNCTION statement. It is stored in the database and can be
deleted with the DROP PROCEDURE or DROP FUNCTION statement.
A subprogram created inside a package is a packaged subprogram. It is stored in the database
and can be deleted only when the package is deleted with the DROP PACKAGE statement. We
will discuss packages in the chapter 'PL/SQL - Packages'.
PL/SQL subprograms are named PL/SQL blocks that can be invoked with a set of parameters.
PL/SQL provides two kinds of subprograms −
 Functions − These subprograms return a single value; mainly used to compute and return
a value.
 Procedures − These subprograms do not return a value directly; mainly used to perform
an action.

Program 1:

SQL> set serveroutput on;


SQL> create or replace procedure p1 as
2 begin
3 dbms_output.put_line('welcome');
4 end;
5 /

Procedure created.

SQL> execute p1;


welcome

PL/SQL procedure successfully completed.

Program 2:

SQL> create PROCEDURE findMin(x IN number, y IN number, z OUT number) IS


2 BEGIN
3 IF x < y THEN
4 z:= x;
5 ELSE
6 z:= y;
7 END IF;
8 END;
9 /

Procedure created.

SQL> declare
2 a number;
3 b number;
4 c number;
5 begin
6 a:=23;
7 b:=4;
8 findMin(a,b,c);
9 dbms_output.put_line('Minimum value is:'||c);
10 end;
11 /
Minimum value is:4

PL/SQL procedure successfully completed.

SQL>
Program 3:

SQL>set serveroutput on;

SQL> create table emp22(id number,name varchar(20),designation varchar(20),salary number);

Table created.
SQL> insert into emp22 values(3,'john','manager',100000);

1 row created.
SQL> insert into emp22 values(3,'jagan','hr',400000);

1 row created.

SQL> CREATE OR REPLACE FUNCTION totalemployee return number as


2 total number;
3 begin
4 SELECT count(*) into total from emp22;
5 Return total;
6 end;
7
8 /

Function created.

SQL> declare
2 a number:=0;
3 begin
4 a:=totalemployee();
5 dbms_output.put_line('Total employees are '||a);
6 end;
7 /
Total employees are 2

PL/SQL procedure successfully completed.

Result:
Thus the procedure for finding minimum value and function to count number of employees is
executed successfully.

Exp.5
Implicit and explicit Cursors
Aim:
To create PL/SQL procedure using an implicit and explicit cursor in SQL.

Implicit Cursors:
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed,
when there is no explicit cursor for the statement. Programmers cannot control the implicit
cursors and the information in it.
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is
associated with this statement. For INSERT operations, the cursor holds the data that needs to be
inserted. For UPDATE and DELETE operations, the cursor identifies the rows that would be
affected.
In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which always
has attributes such as %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT.
S.No Attribute & Description
%FOUND
1 Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more rows
or a SELECT INTO statement returned one or more rows. Otherwise, it returns FALSE.
%NOTFOUND
2 The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or DELETE
statement affected no rows, or a SELECT INTO statement returned no rows. Otherwise, it
returns FALSE.
%ISOPEN
3 Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor
automatically after executing its associated SQL statement.
%ROWCOUNT
4 Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement, or
returned by a SELECT INTO statement.

Table creation:
Create table employee22(empid number,empname varchar(20),empdept varchar(20),salary
number);

Example:

DECLARE
total number(2);
BEGIN
UPDATE employee22 SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no employees selected');
ELSIF sql%found THEN
total := sql%rowcount;
dbms_output.put_line( total || ' employees selected ');
END IF;
END;
/

Output:

Explicit cursor:
Explicit cursors are programmer-defined cursors for gaining more control over the context area.
An explicit cursor should be defined in the declaration section of the PL/SQL Block. It is created
on a SELECT Statement which returns more than one row.
The syntax for creating an explicit cursor is −
CURSOR cursor_name IS select_statement;
Working with an explicit cursor includes the following steps −
 Declaring the cursor for initializing the memory
 Opening the cursor for allocating the memory
 Fetching the cursor for retrieving the data
 Closing the cursor to release the allocated memory
Example:
DECLARE
id employee22.empid%type;
name employee22.empname%type;
dept employee22.empdept%type;

sal employee22.salary%type;
CURSOR c is
SELECT empid, empname, empdept,salary FROM employee22;
BEGIN
OPEN c;
LOOP
FETCH c into id, name, dept,sal;
EXIT WHEN c%notfound;
dbms_output.put_line(id|| ' ' ||name || ' ' || dept||’ ‘|| sal);
END LOOP;
CLOSE c;
END;
/

Output:

Result:
Thus the PL/SQL procedures using implicit and explicit cursor is executed successfully.

Exp.6.
Triggers
Aim:
To create PL/SQL procedure for trigger.
Trigger :
Triggers are stored programs, which are automatically executed or fired when some events
occur. Triggers are, in fact, written to be executed in response to any of the following events −
 A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
 A database definition (DDL) statement (CREATE, ALTER, or DROP).
 A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
Triggers can be defined on the table, view, schema, or database with which the event is
associated.

Table creation:
Create table employee22(empid number,empname varchar(20),empdept varchar(20),salary
number);

Example:

CREATE OR REPLACE TRIGGER display_salary


BEFORE DELETE OR UPDATE ON employee22
FOR EACH ROW
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;
/
Output:

Result:
Thus , the PL/SQL procedure using trigger is executed successfully.

Exp.no.7

EXCEPTION HANDLING

Aim:
To create PL/SQL procedure with exception handling.

Exception:
An exception is an error condition during a program execution. PL/SQL supports programmers
to catch such conditions using EXCEPTION block in the program and an appropriate action is
taken against the error condition. There are two types of exceptions −
 System-defined exceptions
 User-defined exceptions

Syntax for Exception Handling

The general syntax for exception handling is as follows. Here you can list down as many
exceptions as you can handle. The default exception will be handled using WHEN others THEN

DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling goes here >
WHEN exception1 THEN
exception1-handling-statements
WHEN exception2 THEN
exception2-handling-statements
WHEN exception3 THEN
exception3-handling-statements
........
WHEN others THEN
exception3-handling-statements
END;

Pre-defined Exceptions
PL/SQL provides many pre-defined exceptions, which are executed when any database rule is
violated by a program. For example, the predefined exception NO_DATA_FOUND is raised
when a SELECT INTO statement returns no rows. The following table lists few of the
important pre-defined exceptions −

Exception Description

It is raised when attempts are made to make a cursor operation that


INVALID_CURSOR
is not allowed, such as closing an unopened cursor.

It is raised when the conversion of a character string into a number


INVALID_NUMBER
fails because the string does not represent a valid number.

It is raised when a program attempts to log on to the database with


LOGIN_DENIED
an invalid username or password.

NO_DATA_FOUND It is raised when a SELECT INTO statement returns no rows.

It is raised when a database call is issued without being connected


NOT_LOGGED_ON
to the database.

ROWTYPE_MISMATCH It is raised when a cursor fetches value in a variable having


incompatible data type.

It is raised when a SELECT INTO statement returns more than one


TOO_MANY_ROWS
row.

It is raised when an arithmetic, conversion, truncation, or


VALUE_ERROR
sizeconstraint error occurs.

ZERO_DIVIDE It is raised when an attempt is made to divide a number by zero.

User-defined Exceptions
PL/SQL allows you to define your own exceptions according to the need of your program. A
user-defined exception must be declared and then raised explicitly, using a RAISE statement.
The syntax for declaring an exception is −

DECLARE
my-exception EXCEPTION;

System-defined exceptions:

DECLARE
id employee.empid%type := 8;
name employee.empname%type;
sal employee.salary%type;
BEGIN
SELECT empname, salary INTO name, sal FROM employee WHERE empid = id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| name);
DBMS_OUTPUT.PUT_LINE ('salary: ' || sal);

EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such employee');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
User-defined exceptions:

DECLARE
id employee.empid%type := &id;
name employee.empname%type;
sal employee.salary%type;

ex_invalid_id EXCEPTION;
BEGIN
IF id <= 0 THEN
RAISE ex_invalid_id;
ELSE
SELECT empname, salary INTO name, sal FROM employee WHERE empid = id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || sal);
END IF;

EXCEPTION
WHEN ex_invalid_id THEN
dbms_output.put_line('ID must be greater than zero!');
WHEN no_data_found THEN
dbms_output.put_line('No such employee!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/

Result:
Thus , the PL/SQL procedure with exception handling is executed successfully.

Exp. No.8:

Database Design using ER modeling, normalization


Aim:

To design Database using ER modeling, normalization

Procedure:

Entity relationship diagram (ERD) is one of the most widely used technique for data modeling.
Data modeling is an essential component of database design and development. It provides a
means to analyze business requirements so as to standardize organizational vocabulary, enforce
business rules, and ensure adequate data quality. Data modeling is performed during the initial
phases of the database development process (also referred as database life cycle) as shown in
Figure 1. During this process, the top two phases are concerned with the information content of
the database, while the last two phases are concerned with the implementation of the database on
some commercial DBMS.
Figure 1

During the conceptual data modeling phase, data requirements are expressed through an ERD.
The conceptual data modeling phase in general is independent of a DBMS. The logical design
phase transforms the conceptual data model into a format understandable to DBMS. This phase
may also enhance or refine the data model (ERD) of the previous phase to ensure efficient
utilization of the database. Since most of the commercial DBMS are based on the relational
model, the end product of this phase is relational model design.

One of the ways an ERD is enhanced during the logical design phase is through the process of
normalization. Normalization is one of the key tenets in relational model design. It is the process
of removing redundancy in a table so that the table is easier to modify . It usually involves
dividing an entity table into two or more tables and defining relationships between the tables.
The objective is to isolate data so that additions, deletions, and modifications of an attribute can
be made in just one table and then propagated through the rest of the database via the defined
relationships.

Normalization utilizes association among attributes within an entity table to accomplish its
objective. Since an ERD also utilizes association among attributes as a basis to identify entity
type structure, it is possible to apply normalization principles during the conceptual data
modeling phase. Performing normalization during ERD development can improve the conceptual
model, and speed its implementation. This paper outlines the application of normalization
principles to ERD development during the conceptual modeling phase. There are various
standards for ERD. In this paper, the Crow’s Foot notation is utilized.

Application of Normalization to ERD

Data modeling is an iterative process. Generally a preliminary data model is constructed which is
then refined many times. There are many guidelines (rules) for refining an ERD. Some of these
rules are as follows (Mannino, 2006):

1. Transform attributes into entity types. This transformation involves the addition of an
entity type and a 1-M (one-to-many) relationship.
2. Split compound attributes into smaller attributes. A compound attribute contains multiple
kinds of data.
3. Expand entity types into two entity types and a relationship. This transformation can be
useful to record a finer level of detail about an entity.
4. Transform a weak entity type into a strong entity type. This transformation is most useful
for associative entity types.
5. Add historical details to a data model. Historical details may be necessary for legal as
well as strategic reporting requirements. This transformation can be applied to attributes
and relationships.
6. Add generalization hierarchies by transforming entity types into generalization hierarchy.

Application of normalization principles toward ERD development enhances these guidelines. To


understand this application (i) representation of dependency concepts in an ERD is outlined,
followed by (ii) representation of normal forms toward the development of entity type structure.
Guidelines for identification of various dependencies is avoided in the paper so as to focus more
on their application. Only the first four normal forms and the Boyce-Codd normal forms are
considered.

Representation of Dependencies

Functional dependency in an entity type occurs if one observes the association among the entity
identifier and other attributes as reflected in an entity instance. Each entity instance represents a
set of values taken by the non entity identifier attributes for each primary key (entity identifier)
value. So, in a way an entity instance structure also reflects an application of the functional
dependency concept. For example, the Student entity type of Figure 2 can represent the
functional dependency SID ?Name, Street, City, Zip.
Figure 2

Each entity instance will now represent the functional dependency among the entity attributes as
shown in Figure 3.

Figure 3

During requirement analysis, some entity types may be identified through functional
dependencies, while others may be determined through database relationships. For example, the
statement, “A faculty teaches many offerings but an offering is taught by one faculty” defines
entity type Faculty and Offerings. Another important consideration is to distinguish when one
attribute alone is the entity identifier versus a composite entity identifier. A composite entity
identifier is an entity identifier with more than one attribute. A functional dependency in which
the determinant contains more than one attribute usually represents a many-to-many relationship,
which is more addressed through higher normal forms. The notion of having a composite entity
identifier is not very common, and often times is a matter of expediency, rather than good entity
structure or design.

Transitive dependency in an entity type occurs if non entity identifier attributes have dependency
among themselves. For example, consider the modified Student entity type as shown in Figure 4.
Figure 4

In this entity type, suppose there is a functional dependency BuildingName ? Fee. Existence of
BuildingName ? Fee dependency implies that the value assigned to the Fee attribute is fixed for
distinct BuildingName attribute values. In other words, the Fee attribute values are not specific to
the SID value of a student, but rather the BuildingName value. The entity instance of transitive
dependency is shown in Figure 5.

Figure 5

Multi-valued dependency equivalency in ERD occurs when attributes within an entity instance
have more than one value. This is a situation when some attributes within an entity instance have
maximum cardinality of N (more than 1). When an attribute has multiple values in an entity
instance, it can be setup either as a composite key identifier of the entity type, or split into a
weak entity type. For example, consider the following entity type Student Details as shown in
Figure 6.

Figure 6
The Student Details entity type has a composite entity identifier consisting of three attributes –
SID, MajorMinor, and Activity. The composition of entity identifier is due to the fact that a
student has multiple MajorMinor values along with being involved in multiple activities.
However, a student has only one value for Name, Street, City, Zip attributes based on the
functional dependency SID, MajorMinor, Activity ? Name, Street, City, Zip. The multi-valued
dependency affects the key structure. So, in the Student Details entity type, there can be an MVD
SID ?? MajorMinor, Activity. This means that a SID value is associated with multiple values of
MajorMinor and Activity attributes, and together they determine other attributes. The entity
instance of Student Details entity type is shown Figure 7.

Figure 7

2.2 Normalized ERD

Now we utilize the representation of dependency concepts in ERD toward their use in the
application of normal forms. Each normal form rule and its application is outlined.

First Normal Form (1NF)


The first normal form rule is that there should be no nesting or repeating groups in a table. Now
an entity type that contains only one value for an attribute in an entity instance ensures the
application of first normal form for the entity type. So in a way any entity type with an entity
identifier is by default in first normal form. For example, the entity type Student in Figure 2 is in
first normal form.

Second Normal Form (2NF)


The second normal form rule is that the key attributes determine all non-key attributes. A
violation of second normal form occurs when there is a composite key, and part of the key
determines some non-key attributes. The second normal form deals with the situation when the
entity identifier contains two or more attributes, and the non-key attribute depends on part of the
entity identifier. For example, consider the modified entity type Student as shown in Figure 8.
The entity type has a composite entity identifier of SID and City attributes.
Figure 8

An entity instance of this entity type is shown in Figure 9. Now, if there is a functional
dependency City ? Status, then the entity type structure will violate the second normal form.

Figure 9

To resolve the violation of the second normal form a separate entity type City with one-to-many
relationship is created as shown in Figure 10. The relationship cardinalities can be further
modified to reflect organizational working. In general, the second normal form violation can be
avoided by ensuring that there is only one attribute as an entity identifier.

Figure 10

Third Normal Form (3NF)


The third normal form rule is that the non-key attributes should be independent. This normal
form is violated when there exists a dependency among non-key attributes in the form of a
transitive dependency. For example consider the entity type Student as shown in Figure 4. In this
entity type, there is a functional dependency BuildingName ? Fee that violates the third normal
form.
Transitive dependency is resolved by moving the dependency attributes to a new entity type with
one-to-many relationship. In the new entity type the determinant of the dependency becomes the
entity identifier. The resolution of the third normal form is shown in Figure 11. The relationship
cardinalities can be further modified to reflect organizational working.

Figure 11

Boyce-Codd Normal Form (BCNF)


The Boyce-Codd normal form (BCNF) extends the third normal form. The Boyce-Codd normal
form rule is that every determinant is a candidate key. Even though Boyce-Codd normal form
and third normal form generally produce the same result, Boyce-Codd normal form is a stronger
definition than third normal form. Every table in Boyce-Codd normal form is by definition in
third normal form. Boyce-Codd normal form considers two special cases not covered by third
normal form:

1. Part of a composite entity identifier determines part of its attribute, and


2. a non entity identifier attribute determines part of an entity identifier attribute.

These situations are only possible if there is a composite entity identifier, and dependencies exist
from a non-entity identifier attribute to part of the entity identifier. For example, consider the
entity type StudentConcentration as shown in Figure 12. The entity type is in third normal form,
but since there is a dependency FacultyName ? MajorMinor, it is not in Boyce-Codd normal
form.

Figure 12

To ensure that StudentConcentration entity type stays in Boyce-Codd normal form, another
entity type Faculty with one-to-many relationship is constructed as shown in Figure 13. The
relationship cardinalities can be further modified to reflect organizational working.
Figure 13

Fourth Normal Form (4NF)


Fourth normal form rule is that there should not be more than one multi-valued dependency in a
table. For example, consider the Student Details entity type shown in Figure 6. Now, during
requirements analysis if it is found that the MajorMinor values of a student are independent of
the Activity performed by the student, then the entity type structure will violate the fourth normal
form. To resolve the violation of the fourth normal form separate weak entity types with
identifying relationships are created as shown in Figure 14. The StudentFocus and
StudentActivity entity types are weak entity types. The relationship cardinalities can be further
modified to reflect organizational working. It is now presumed that the Student entity type has
the functional dependency SID ? Name, Street, City, Zip.

Figure 14

Result:
Thus database is designed with normalization.
Exp.no. 9.
Database Connectivity with Front End Tools

Aim :

To connect database with netbeans IDE.

Procedure:

1. Start the Oracle database.


2. Open the Services window (Window > Services or Ctrl-5;⌘-5 on Mac). In the Services
window, right-click the Databases node and choose New Connection.

3. In the New Connection wizard, select Oracle Thin in the Driver dropdown list.
4. Click Add and locate the ojdbc6.jar file that you previously downloaded. Click Next.
5. In the Customize Connection panel of the wizard, enter the following values and click Next.
Name Value
Driver Name Oracle Thin (with Service ID (SID))
localhost or 127.0.0.1.
Note: In the case of a remote connection, provide the IP
Host
address or resolvable hostname of the machine where the
database is installed.
Port 1521 (default)
XE (default SID for Oracle Database XE).
Service ID (SID) Note: If you are connecting to a remote database, ask the
database administrator to provide you with the database SID.

Enter the username.


Username For the purpose of our tutorial, enter system (the default
database administrator account) and password that you used
during database installation.
Password Enter the password for the selected username.
6. Click Test Connection to confirm that the IDE is able to connect to the database. Click
Next.
If the attempt is successful, the message "Connection succeeded" is displayed in the
wizard.

7. Select HR in the Select Schema dropdown list. Click Finish.

Note: You need to unlock the HR schema before you can access it in NetBeans.
Unlocking the HR database is described in the Oracle Database XE Getting Started
tutorial.

The new connection will appear under the Databases node in the Services window. You can
expand it and start browsing the database object's structure.
Change the display name for the connection node: choose Properties from the node's popup
menu and click the ellipsis button for the Display Name property. Enter OracleDB as the Display
Name and click OK.
Note. Although the steps above demonstrate the case of connecting to a local database instance,
the steps for connecting to a remote database are the same. The only difference is that instead of
specifying localhost as the hostname, enter the IP address or hostname of the remote machine
where Oracle Database is installed.

Result:

Thus the database is connected with netbeans IDE.

Ex.No : 10

Employee Management System

AIM :
To implement the project for Employee management system.

Description :
Employee Management System is used to maintain the detail of employees of an
organization. HR can view the details department wise. HR can delete the employees.HR can
update the employees details. HR can add new employees.

Tables :
o Employee(empno number primary key , empname varchar(20) , department
varchar(20) , salary number)

SQL> select *from employee;

EMPID EMPNAME EMPDEPT SALARY


---------- -------------------- -------------------- ----------
1 rekha cse 30000
2 renu cse 70000
3 elamathi ece 90000
4 rahul ece 79990

Net beans:

Add jar file.


Right click on package---select properties ----select libraries- add jar file(ojdbc7).

Right click on package --- select new----select JFrame forms.


Design forms:

Procedure:
1. Code for components in GUI will come automatically.
2. Do oracle connectivity. (click on services----right click on database—select new
connection—
Select oracle thin driver----give service id as orcl.---give username and password.---click
test connection.

3. Import javax.swing and java.sql


4. Double click on button in forms and type the coding

Coding:

private void deleteActionPerformed(java.awt.event.ActionEvent evt) {


try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:orcl","system","manager
");

Statement stmt=con.createStatement();

String a=JOptionPane.showInputDialog(null,"Enter Employee id");


int temp=0;
ResultSet rs=stmt.executeQuery("select * from employee");
while(rs.next())
{
if (rs.getString(1).equals(a))
{
temp=1;

}
}

if (temp==1)
{
String query="delete from employee where empid= " + a ;
stmt.execute(query);
JOptionPane.showMessageDialog (null,"employee record deleted");

}
else

JOptionPane.showMessageDialog (null,"employee record not found");

con.close();
}

catch(SQLException ex)
{
JOptionPane.showMessageDialog (null,ex);

} catch (ClassNotFoundException ex) {

private void salaryActionPerformed(java.awt.event.ActionEvent evt) {


// TODO add your handling code here:
}

private void nameActionPerformed(java.awt.event.ActionEvent evt) {


// TODO add your handling code here:
}

private void addbuttonActionPerformed(java.awt.event.ActionEvent evt) {


try
{

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:orcl","system","manager
");

Statement stmt=con.createStatement();
String query="insert into employee values( "
+ id.getText()+", '"+name.getText()+"' , '"+department.getText()+"' ,"
+salary.getText()+")";

//String query ="insert into employee values(34,'mala','cse',234324)";


stmt.execute(query);

JOptionPane.showMessageDialog (null,"employee added");

id.setText(null);
name.setText(null);
department.setText(null);
salary.setText(null);

//con.close();

catch(SQLException ex)
{
JOptionPane.showMessageDialog (null,ex);

} catch (ClassNotFoundException ex) {

private void addbuttonMouseClicked(java.awt.event.MouseEvent evt) {

private void searchActionPerformed(java.awt.event.ActionEvent evt) {


try{

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:orcl","system","manager
");

Statement stmt=con.createStatement();
String a=JOptionPane.showInputDialog(null,"Enter Employee id");

ResultSet rs=stmt.executeQuery("select * from employee");


while(rs.next())
{
if (rs.getString(1).equals(a))
{
id.setText(rs.getString(1));
name.setText(rs.getString(2));
department.setText(rs.getString(3));
salary.setText(rs.getString(4));

}
}

}
catch(SQLException ex)
{
JOptionPane.showMessageDialog (null,ex);

} catch (ClassNotFoundException ex) {

private void updateActionPerformed(java.awt.event.ActionEvent evt) {

try
{

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:orcl","system","manager
");

Statement stmt=con.createStatement();
String query="update employee set empid= " + id.getText()+",empname='"
+name.getText()+"' , empdept='"+department.getText()+"' ,salary="
+salary.getText()+"where empid= " + id.getText();

//String query ="insert into employee values(34,'mala','cse',234324)";


stmt.executeQuery(query);

JOptionPane.showMessageDialog (null,"employee details updated");

id.setText(null);
name.setText(null);
department.setText(null);
salary.setText(null);

con.close();

catch(SQLException ex)
{
JOptionPane.showMessageDialog (null,ex);

} catch (ClassNotFoundException ex) {

Result:

Thus the Employee project is completed.

You might also like