Download as pdf or txt
Download as pdf or txt
You are on page 1of 68

Sub.

Code: 20CS4L1 Year: II


Sub. Name: Database Management Systems Laboratory Semester: IV

K.L.N. COLLEGE OF ENGINEERING


Pottapalayam.P.O, Sivagangai -630612.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA SCIENCE

20CS4L1 DATABASE MANAGEMENT SYSTEMS LABORATORY


II YEAR / IV SEMESTER

PREPARED BY

Mr.B.Anandasabarirajan, BE,ME

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV

SYLLABUS

DATABASE MANAGEMENT SYSTEMS L T P C


20CS4L1 LABORATORY 0 0 4 2

OBJECTIVES:
 To write and debug Database commands.
 To implement advanced query in Database tool.
 To use functions and procedures for implementing simple logics in Database.
 To design real time applications using front end tool and Database.
 To implement Database connectivity for real time application.

LIST OF EXPERIMENTS
1. Data Definition and Data Manipulation Language Commands.
2. Data Control and Transaction Control Language Commands.
3. Aggregate Functions and Set Operations.
4. Nested Subqueries and Join Queries.
5. Views, Indexes and Synonyms.
6. Study of PL/SQL programs
7. PL/SQL - procedures
8. PL/SQL - Functions
9. PL/SQL - Triggers
10. PL/SQL - Cursor
11. Front end application development – Create Forms, Menu and Reports.
12. Implementation of Database Connectivity

TOTAL: 60 PERIODS

COURSE OUTCOMES:
On Completion of the course, the students should be able to:
 Develop simple Database using DDL, DML and TCL commands.
 Create Relational Database for real time application through Database constraints.
 Write and execute complex queries using subqueries and join queries.
 Develop PL/SQL programs to implement simple logics using Stored Procedure, Functions, Triggers and
Cursor.

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
 Design a front end application to display forms, menu and reports.
 Design real time applications with Database Connectivity.

LIST OF EQUIPMENT FOR A BATCH OF 30 STUDENTS:


SOFTWARE:
 Oracle/Mysql/Visual Basics/Netbeans IDE

20CS4L1 - DATABASE MANAGEMENT SYSTEMS LAB

LIST OF EXPERIMENTS
1. Data Definition and Data Manipulation Language Commands.
2. Data Control and Transaction Control Language Commands.
3. Aggregate Functions and Set Operations.
4. Nested Subqueries and Join Queries.
5. Views, Indexes and Synonyms.
6. Study of PL/SQL programs
7. PL/SQL - procedures
8. PL/SQL - Functions
9. PL/SQL - Triggers
10. PL/SQL - Cursor
11. Front end application development – Create Forms, Menu and Reports.
12.Implementation of Database Connectivity

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
EX. NO: 1 DATA DEFINITION COMMANDS, DATA MANIPULATION COMMANDS
FOR INSERTING, DELETING, UPDATING AND RETRIEVING TABLES AND
TRANSACTION CONTROL STATEMENTS
AIM
To create a database and to perform Data Definition Commands, Data Manipulation Commands
for inserting, deleting, updating and retrieving Tables and Transaction Control statements.

DDL statements

1. CREATE – is used to create the database or its objects.


2. DROP – is used to delete objects from the database.
3. ALTER – is used to alter the structure of the database.
4. TRUNCATE – is used to remove all records from a table, including all spaces allocated for the
records are removed.
5. COMMENT – is used to add comments to the data dictionary.
6. RENAME – is used to rename an object existing in the database.

DDL COMMANDS

SQL> create table stud (sname varchar2(30), sid varchar2(10), sage number(2), sarea varchar2(20));
Table created.

SQL> desc stud;


Name Null? Type
SNAME VARCHAR2(30)
SID VARCHAR2(10)
SAGE NUMBER(2)
SAREA VARCHAR2(20)

SQL>alter table stud modify ( sage number(10));


Table altered.

SQL> alter table stud add ( sdeptvarchar2(20));


Table altered.

SQL> desc stud;


Name Null? Type
SNAME VARCHAR2(30)
SID VARCHAR2(10)
SAGE NUMBER(10)
SAREA VARCHAR2(20)
SDEPT VARCHAR2(20)

SQL> alter table stud drop (sdept varchar2(20));


Table altered.

SQL> desc studs;

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
Name Null? Type
SNAME VARCHAR2(30)
SID VARCHAR2(10)
SAGE NUMBER(10)
SAREA VARCHAR2(20)

SQL> truncate table studs;


Table truncated.

SQL> desc studs;

Name Null? Type


SNAME VARCHAR2(30)
SID VARCHAR2(10)
SAGE NUMBER(10)
SAREA VARCHAR2(20)
SDEPT VARCHAR2(20)

SQL> drop table studs;


Table dropped.

SQL> rename table studs toold;


Table renamed.

SQL> desc studs;


Table studs doesn't exist.

DML statements

1. SELECT – is used to retrieve data from the database.


2. INSERT – is used to insert data into a table.
3. UPDATE – is used to update existing data within a table.
4. DELETE – is used to delete records from a database table.

DESCRIPTION
 THE ORACLE TABLE - DUAL - Dual is a small oracle table which consists of only one row
and one column and contains the value X in that column.
 INSERT - This command is used to insert values into the table.
 SELECT - This command is used to display the contents of the table or those of a particular
column. 
 RENAME - This command renames the name of thetable.
 ARITHMETIC OPERATIONS - Various operations such as addition, multiplication,
subtraction and division can be performed using the numbers available in the table.
 DISTINCT - This keyword is used along with select keyword to display unique values from the specified
column. It avoids duplicates during display.
 ORDER BY CLAUSE - The order by clause arranges the contents of the table in ascending order (by

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
default) or in descending order (if specified explicitly) according to the specified column.
 CONCATENATION OPERATOR - This combines information from two or more columns in a
sentence according to the formatspecified.

LOGICAL OPERATORS

 AND : The oracle engine will process all rows in a table and displays the result only when all of
the conditions specified using the AND operator are specified.
 OR : The oracle engine will process all rows in a table and displays the result only when any of
the conditions specified using the OR operators are satisfied. 
 NOT : The oracle engine will process all rows in a table and displays the result only when none
of the conditions specified using the NOT operator are specified.
 BETWEEN : In order to select data that is within a range of values, the between operator is used.
(AND should be included)

PATTERN MATCH

 LIKE PREDICATE : The use of like predicate is that it allows the comparison of one string value
with another string value, which is not identical. This is achieved by using wildcard characters
which are % and _. The purpose of % is that it matches any string and _ matches any single
character.
 IN AND NOT IN PREDICATE : The arithmetic operator = compares a single value to another
single value. In case a value needs to be compared to a list of values then the in predicate is used.
The not in predicate is the opposite of the in predicate. This will select all the rows whose values do not
match all of the values in the list.

NUMERIC FUNCTIONS
 ABS: It returns the absolute value of 'n'.
 POWER: It returns m raised to nth power. n must be an integer else an error isreturned.
 ROUND: It returns n rounded to m places right of the decimal point. If m is omitted, n is rounded
to zero places. m must be aninteger.
 SQRT: It returns square root of n. n should be greater thanzero.

STRING FUNCTIONS
 LOWER: It returns char with letters in lower case.
 INITCAP: It returns char with the first letter in upper case.
 UPPER: It returns char with all letters forced to upper case.
 SUBSTR: It returns a portion of char beginning at character m, exceeding up to n characters. If n
is omitted result is written up to the end character. The 1stposition of char is one.
 LENGTH: It returns the length of char
 LTRIM: It removes characters from the left of char with initial characters removed up to the 1st
character not in set.
 RTRIM: It returns char with final characters removed after the last character not in the set. Set is
optional. It defaults to spaces.

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV

 LPAD: It returns char1, left padded to length n with the sequence of characters in char2. char2
defaults to blanks.
 RPAD: It returns char1, right padded to length n with the characters in char2, replicated as many
times as necessary. If char2 is omitted, it is padded with blanks.

AGGREGATE FUNCTIONS
 AVG (N): It returns average value of n ignoring null values.
 MIN (EXPR): It returns minimum value of the expression.
 COUNT (EXPR): It returns the number of rows where expression is not null.
 COUNT (*): It returns the number of rows in the table including the duplicates and those with null
values. 
 MAX (EXPR): It returns maximum value of the expression.
 SUM(N): It returns sum of values of n.

CONVERSION FUCTIONS

 TO_NUMBER(CHAR): It converts the char value containing a number to a value of number datatype.
 TO_CHAR(N,FMT): It converts a value of number data type to a value of char data type, using
the optional format string. It accepts a number n and a numeric format fmt in which the number has to appear. If
fmt is omitted, n is converted to a char value exactly long enough to hold significant digits.
 TO_CHAR(DATE, FMT): It converts a value of data type to char value. It accepts a date as well
as the format in which the date has to appear. Fmt must be a date format. If fmt is omitted, date is the default date
format.

DATE FUNCTIONS

 SYSDATE : The sysdate is a pseudo column that contains the current date and time. It requires
no arguments when selected from the table dual and returns the currentdate.
 ADD_MONTHS(D,N): It returns date after adding the number of months specified with the
function.
 LAST_DAY(D): It returns the last date of the month specified with the function
 MONTHS_BETWEEN(D1,D2): It returns number of months between D1 and D2.
 NEXT_DAY(DATE, CHAR): It returns the date of the first week day named by char . char must
be a day of theweek.

GROUP BY CLAUSE

The group by clause is another section of the select statement. This optional class tells oracle to group rows
based on distinct values that exists for specified columns.

HAVING CLAUSE
The having clause can be used in conjunction with the group by clause. Having imposes a condition on the
group by clause, which further filters the groups created by the group by clause.

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
SET OPERATIONS
 UNION CLAUSE: Multiple queries can be put together and their output combined usingthe
union clause. The union clause merges the output of two or more queries into a single set of rows and columns.
 INTERSECT CLAUSE: Multiple queries can be put together and their output can be combined
using the intersect clause. The intersect clause outputs only rows produced by both the queries intersected. The
output in an intersect clause will include only those rows that are retrieved by both the queries.

DML COMMANDS
CREATION OF TABLE
SQL>create table stud (sname varchar2(30), sid varchar2(10), sage number(10), sarea varchar2(20), sdept
varchar2(20));
Table created.
INSERTION OF VALUES INTO THE TABLE
SQL> insert into stud values ('ashwin',101,19,'anna nagar','aeronautical');
1 row created.

SQL> select * from stud;

SNAME SID SAGE SAREA SDEPT

ashwin 101 19 anna nagar aeronautical


bhavesh 102 18 nungambakkam marine
pruthvik 103 20 anna nagar aerospace
charith 104 20 kilpauk mechanical

RENAMING THE TABLE 'STUD'


SQL> rename stud to studs;
Table renamed.
ARITHMETIC OPERATION
SQL> select sname, sid+100 "stid" from studs;
SNAME stid
ashwin 201
bhavesh 202
pruthvik 203
charith 204

CONCATENATION OPERATOR

SQL> select sname || ' is a ' || sdept || ' engineer. ' AS "PROFESSION" from studs;

PROFESSION

ashwin is a aeronautical engineer. bhavesh is a marine engineer.


pruthvik is a aerospace engineer.
charith is a mechanical engineer.

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
DISPLAY ONLY DISTINCT VALUES
SQL> select distinct sarea from studs;

SAREA

anna nagar
kilpauk
nungambakkam
USING THE WHERE CLAUSE
SQL> select sname,sage from studs where sage<=19;
SNAME SAGE

ashwin 19
bhavesh 18
BETWEEN OPERATOR
SQL> select sname,sarea, sid from studs where sid between 102 and 104;
SNAME SAREA SID

bhavesh nungambakkam 102


pruthvik anna nagar 103
charith kilpauk 104

IN PREDICATE
SQL> select sname,sarea , sid from studs where sid in(102,104);
SNAME SAREA SID
bhavesh nungambakkam 102
charith kilpauk 104

PATTERN MATCHING
SQL> select sname, sarea from studs where sarea like '%g%';
SNAME SAREA
ashwin anna nagar
bhavesh nungambakkam
pruthvik anna nagar

LOGICAL AND OPERATOR


SQL> select sname ,sid from studs where sid>102 and sarea='anna nagar';
SNAME SID
pruthvik 103

LOGICAL OR OPERATOR
SQL> select sname ,sid from studs where sid>102 or sarea='anna nagar';
SNAME SID

Ashwin 101
Pruthvik 103
charith 104

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
NOT IN PREDICATE
SQL> select sname, sid from studs where sid not in(102,104);
SNAME SID
Ashwin 101
charith 104

UPDATING THE TABLE


SQL> alter table studs add ( spocket varchar2(20) );
Table altered.
SQL> update studs set spocket=750 where sid=101;
1 row updated.
SQL> update studs set spocket=500 where sid=102;
1 row updated.
SQL> update studs set spocket=250 where sid=103;
1 row updated.
SQL> update studs set spocket=100 where sid=104;
1 row updated.

SQL> select * from studs;


SNAME SID SAGE SAREA SDEPT SPOCKET
ashwin 101 19 anna nagar aeronautical 750
bhavesh 102 18 nungambakkam marine 500
pruthvik 103 20 anna nagar aerospace 250
charith 104 20 kilpauk mechanical 100

AGGREGATE FUNCTIONS
SQL> select avg( spocket ) result from studs;
RESULT
400
SQL> select min(spocket) result from studs;
RESULT
100
SQL> select count(spocket) result from studs;
RESULT
4
SQL> select count(*) result from studs;
RESULT
4
SQL> select count(spocket) result from studs where sarea='anna nagar';
RESULT
2
SQL> select max(spocket) result from studs;
RESULT

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
750

SQL> select sum(spocket) result from studs;


RESULT
1600

NUMERIC FUNCTIONS
SQL> select abs(-20) result from dual;

RESULT

20
SQL> select power (2,10) result from dual;
RESULT
1024
SQL> select round(15.359,2) result from dual;
RESULT
15.36
SQL> select sqrt (36) result from dual;
RESULT
6

STRING FUNCTIONS
SQL> select lower('ORACLE') result from dual;
RESULT
oracle
SQL> select upper('oracle') result from dual;
RESULT
ORACLE
SQL> select initcap('Oracle') result from dual;
RESULT
Oracle
SQL> select substr('oracle' ,2 ,5) result from dual;
RESULT
racle
SQL> select lpad('oracle',10,'#') result from dual;
RESULT
####oracle
SQL> select rpad ('oracle',10,'^') result from dual;
RESULT
oracle^^^^

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV

CONVERSION FUNCTIONS
SQL> update studs set sage=to_number(substr(118,2,3));
4 rows updated.

SQL> select * from studs;

SNAME SID SAGE SAREA SDEPT SPOCKET


ashwin 101 18 anna nagar aeronautical 750
bhavesh 102 18 nungambakkam marine 500
pruthvik 103 18 anna nagar aerospace 250
charith 104 18 kilpauk mechanical 100

SQL> select to_char( 17145, '099,999') result from dual;


RESULT
017,145

SQL> select to_char(sysdate,'dd-mon-yyyy') result from dual;


RESULT
16-jul-2008
DATE FUNCTIONS
SQL> select sysdate from dual;
SYSDATE
16- JUL-08
SQL> select sysdate,add_months(sysdate,4) result from dual;

SYSDATE RESULT

16-JUL-08 16-NOV-08

SQL> select sysdate, last_day(sysdate) result from dual;


SYSDATE RESULT
16- JUL-08 31-JUL-08

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

SYSDATE RESULT

16-JUL-08 20-JUL-08

SQL> select months_between('09-aug-91','11-mar-90') result from dual;


RESULT
16.935484

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
GROUP BY CLAUSE
SQL> select sarea, sum(spocket) result from studs group by sarea;
SAREA RESULT

anna nagar 1000


nungambakkam 500
kilpauk 100

HAVING CLAUSE
SQL> select sarea, sum(spocket) result from studs group by sarea having spocket<600;
SAREA RESULT
nungambakkam 500
kilpauk 100
DELETION
SQL> delete from studs where sid=101;
1 row deleted.
SQL> select * from studs;
SNAME SID SAGE SAREA SDEPT SPOCKET

bhavesh 102 18 nungambakkam marine 500


pruthvik 103 18 anna nagar aerospace 250
charith 104 18 kilpauk mechanical 100

CREATING TABLES FOR DOING SET OPERATIONS

TO CREATE PRODUCT TABLE


SQL> create table product(prodname varchar2(30), prodno varchar2(10));
Table created.
SQL> insert into product values('table',10001);
1 row created.
SQL> insert into product values('chair',10010);
1 row created.
SQL> insert into product values('desk',10110);
1 row created.
SQL> insert into product values('cot',11110);
1 row created.
SQL> insert into product values('sofa',10010);
1 row created.
SQL> insert into product values('tvstand',11010);
1 row created.
SQL> select * from product;
PRODNAME PRODNO

table 10001
chair 10010
desk 10110
cot 11110
sofa 10010
tvstand 11010

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV

TO CREATE SALE TABLE


SQL> create table sale(prodname varchar2(30),orderno number(10),prodno varchar2(10));
Table created.
SQL> insert into sale values('table',801,10001);
1 row created.
SQL> insert into sale values('chair',805,10010);
1 row created.

SQL> select * from sale;


PRODNAME ORDERNO PRODNO

table 801 10001


chair 805 10010
desk 809 10110
cot 813 11110
sofa 817 10010

SET OPERATIONS
SQL> select prodname from product where prodno=10010 union select prodname from sale where
prodno=10010;

PRODNAME
chair
sofa
SQL> select prodname from product where prodno=11110 intersect select prodname from sale where
prodno=11110;
PRODNAME
cot

DCL and TCL statements


DESCRIPTION
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
 Revoke
 Commit
 Savepoint
 Rollback
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.

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
COMMIT : It is used to permanently save any transaction into database.
SAVEPOINT: It is used to temporarily save a transaction so that you can rollback to that point
whenever necessary
ROLLBACK: It restores the database to last commited state. It is also use with savepoint command to
jump to a savepoint in a transaction

DCL and TCL COMMAND


GRANT COMMAND
Grant < database_priv [database_priv..] > to <user_name>identifiedby <password>
[,<password..];
Grant <object_priv> | All on <object> to <user | public> [ With Grant Option ];
REVOKE COMMAND
Revoke <database_priv> from <user [, user ] >;
Revoke <object_priv> on <object> from < user | public >;
<database_priv> -- Specifies the system level priveleges to be granted to the users or roles. This includes
create / alter / delete any object of the system.
<object_priv> -- Specifies the actions such as alter / delete / insert / references / execute / select / update for
tables.
<all> -- Indicates all the priveleges.
[ With Grant Option ] - Allows the recipient user to give further grants on the objects.
The privileges can be granted to different users by specifying their names or to all users by using the "Public"
option.

COMMIT:
Commit;
SAVEPOINT:
Savepoint savapoint_name;
ROLLBACK:
Rollback to savepoint_name;

EXAMPLES
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);
SQL> Grant all on employees to abcde;
Grant succeeded.
SQL> Grant select , update , insert on departments to abcde with grant option;
Grant succeeded.
SQL> Revoke all on employees from abcde;
Revoke succeeded.
SQL> Revoke select , update , insert on departments from abcde;
Revoke succeeded.

COMMIT, ROLLBACK and SAVEPOINT:


SQL> select * from class;

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
NAME ID

anu 1
brindha 2
chinthiya 3
divya 4
ezhil 5
fairoz 7
SQL> insert into class values('gayathri',9);
1 row created.
SQL> commit;
Commit complete.
SQL> update class set name='hema' where id='9';
1 row updated.
SQL> savepoint A;
Savepoint created.
SQL> insert into class values('indu',11);
1 row created.
SQL> savepoint B;
Savepoint created.
SQL> insert into class values('janani',13);
1 row created.
SQL> select * from class;
NAME ID

anu 1
brindha 2
chinthiya 3
divya 4
ezhil 5
fairoz 7
hema 9
indu 11
janani 13
9 rows selected.
SQL> rollback to B;
Rollback complete.
SQL> select * from class;
NAME ID

anu 1
brindha 2
chinthiya 3

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV

divya 4
ezhil 5
fairoz 7
hema 9
indu 11
8 rows selected.
SQL> rollback to A;
Rollback complete.
SQL> select * from class;
NAME ID

anu 1
brindha 2
chinthiya 3
divya 4
ezhil 5
fairoz 7
hema 9

RESULT
Thus the creation of database to perform Data Definition Commands, Data Manipulation Commands for
inserting, deleting, updating and retrieving Tables and Transaction Control statements has been implemented and
the output was verified.

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
EX. NO: 2 DATABASE QUERYING – SIMPLE QUERIES, NESTED QUERIES,
SUB QUERIES AND JOINS

AIM
To study the Simple queries, Nested queries, Sub queries and Joins using DML commands.

DESCRIPTION:

JOIN OPERATIONS
 INNER JOIN/ NATURAL JOIN/ JOIN: It is a binary operation that allows us to combine
o certain Selections and a Cartesian product into oneoperation.
 OUTER JOIN: It is an extension of join operation to deal with missing information.
o 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.
o 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.


o Full Outer Join: It combines tuples from both the left and the right relation and pads the
tuples with null values for the missing attributes and hem to the result of the natural join.

TO CREATE SSTUD1 TABLE


SQL> create table sstud1 ( sname varchar2(20) , place varchar2(20));
Table created.
SQL> insert into sstud1 values ( 'prajan','chennai');
1 row created.
SQL> insert into sstud1 values ( 'anand','chennai');
1 row created.
SQL> insert into sstud1 values ( 'kumar','chennai');
1 row created.
SQL> insert into sstud1 values ( 'ravi','chennai');
1 row created.
SQL> select * from sstud1;
SNAME PLACE
prajan chennai
anand chennai
kumar chennai
ravi Chennai

TO CREATE SSTUD2 TABLE

SQL> create table sstud2 ( sname varchar2(20), dept varchar2(10), marks number(10));
Table created.

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
SQL> insert into sstud2 values ('prajan','cse',700);
1 row created.
SQL> insert into sstud2 values ('anand','it',650);
1 row created.
SQL> insert into sstud2 values ('vasu','cse',680);
1 row created.
SQL> insert into sstud2 values ('ravi','it',600);
1 row created.

SQL> select * from sstud2;

SNAME DEPT MARKS

prajan cse 700


anand it 650
vasu cse 680
ravi it 600

NESTED QUERIES
SQL> select sname from sstud1 where sstud1.sname in ( select sstud2.sname from sstud2 );
SNAME
anand
prajan
ravi
SQL> select sname from sstud1 where sstud1.sname not in ( select sstud2.sname from sstud2 );
SNAME
kumar
SQL> select sname from sstud2 where marks > some(select marks from sstud2 where dept='cse');
SNAME
prajan
SQL> select sname from sstud2 where marks >= some (select marks from sstud2 where dept='cse' );
SNAME
prajan
vasu
SQL> select sname from sstud2 where marks > any ( select marks from sstud2 where dept='cse' );
SNAME
prajan
SQL> select sname from sstud2 where marks >= any ( select marks from sstud2 where dept='cse' );
SNAME
prajan
vasu
SQL> select sname from sstud2 where marks > all ( select marks from sstud2 where dept='cse' );
no rows selected

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
SQL> select sname from sstud2 where marks < all ( select marks from sstud2 where dept='cse' );
SNAME
anand
ravi
SQL> select sname from sstud1 where exists ( select sstud2.sname from sstud2 where
sstud1.sname=sstud2.sname );
SNAME
prajan
anand
ravi

SQL> select sname from sstud1 where not exists ( select sstud2.sname from sstud2 where
sstud1.sname=sstud2.sname );
SNAME
kumar

CREATING TABLES FOR DOING JOIN AND NESTED QUERY OPERATIONS


Creating Dept table:
SQL> create table dept(dno number(10),dname varchar(10),loc varchar(10));
Table created.
SQL> insert into dept values(10,'inventory','hyd');
1 row created.
SQL> insert into dept values(20,'finance','bglr');
1 row created.
SQL> insert into dept values(30,'HR','mumbai');
1 row created.

SQL> select * from dept;


DNO DNAME LOC

10 inventory hyd
20 finance bglr
30 HR mumbai

Creating emp2 table:

SQL> create table emp2(eno number(10),ename varchar(10),job varchar(10),Mer(10),dno number(10));


Table created.
SQL> insert into emp2 values(111,'saketh','analyst',444,10);
1 row created.
SQL> insert into emp2 values(222,'sandeep','clerk',333,20);
1 row created.
SQL> insert into emp2 values(333,'jagan','manager',111,10);
1 row created.
SQL> insert into emp2 values(444,'madhu','engineer',222,40);
1 row created.

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
SQL> select * from emp2;
ENO ENAME JOB MGR DNO

111 saketh analyst 444 10


222 sandeep clerk 333 20
333 jagan manager 111 10
444 madhu engineer 222 40

1. Equijoin:
A join which contains an equal to '=' operator in this joins condition
SQL> select eno,ename,job,dname,loc from emp2 e,dept d where e.dno=d.dno;
ENO ENAME JOB DNAME LOC

111 saketh analyst inventory hyd


222 sandeep clerk finance bglr
333 jagan manager inventory hyd
Using Clause:
SQL> select eno,ename,job,dname,loc from emp2 e join dept d using(dno);

ENO ENAME JOB DNAME LOC

111 saketh analyst inventory hyd


222 sandeep clerk finance bglr
333 jagan manager inventory hyd
On Clause:
SQL> select eno,ename,job,dname,loc from emp2 e join dept d on(e.dno=d.dno);
ENO ENAME JOB DNAME LOC

111 saketh analyst inventory hyd


222 sandeep clerk finance bglr
333 jagan manager inventory hyd
2. Non-Equijoin:
A join which contains an operator other than equal to '=' in the join condition.
SQL> select eno,ename,job,dname,loc from emp2 e,dept d where e.dno>d.dno;
ENO ENAME JOB DNAME LOC
222 sandeep clerk I nventory hyd
444 madhu engineer inventory hyd
444 madhu engineer finance bglr
444 madhu engineer HR Mumbai
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 gr;
ENO ENAME JOB DNO

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV

444 saketh engineer 10


333 sandeep manager 20
111 jagan analyst 10
222 madhu clerk 40

4. Natural Join:
It compares all the common columns.

SQL> select eno,ename,job,dname,loc from emp2 natural join dept;


ENO ENAME JOB DNAME LOC

111 saketh analyst inventory hyd


222 sandeep clerk finance bglr
333 jagan manager inventory hyd

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

111 saketh analyst inventory hyd


222 sandeep clerk inventory hyd
333 jagan manager inventory hyd
444 madhu engineer inventory hyd
111 saketh analyst finance bglr
222 sandeep clerk finance bglr
333 jagan manager finance bglr
444 madhu engineer finance bglr
111 saketh analyst HR mumbai
222 sandeep clerk HR mumbai
333 jagan manager HR mumbai
444 madhu engineer HR mumbai
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 sidetable.
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(+);

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV

ENO ENAME JOB DNAME LOC

333 jagan manager inventory hyd


111 saketh analyst inventory hyd
222 sandeep clerk finance bglr
444 madhu engineer

Right Outer Join:


This will display the all matching records and the records which are in right hand side table those that
are not in left hand sidetable.
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;
ENO ENAME JOB DNAME LOC

111 saketh analyst inventory hyd


222 sandeep clerk finance bglr
333 jagan manager inventory hyd
HR mumbai
Full Outer Join:
This will display the all matching records and the non matching records from both tables.
SQL> select eno,ename,job,dname,loc from emp2 e full outer join dept d on(e.dno= d.dno);

ENO ENAME JOB DNAME LOC

333 jagan manager inventory hyd


111 saketh analyst inventory hyd
222 sandeep clerk finance bglr
444 madhu engineer
HR Mumbai

RESULT

The Simple queries, Nested queries, Sub queries and Joins using DML commands were executed
and the output was verified.

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
EX. NO 3: CREATION OF VIEWS, SYNONYMS, SEQUENCE
AIM:

To create views, synonyms and sequences using DDL, DML and DCL
Statements.

DESCRIPTION:

Views
 A database view is a logical or virtual table based on a query. It is useful to think of a
view as a stored query. Views are queried just like tables.
 A DBA or view owner can drop a view with the DROP VIEW command.
TYPES OF VIEWS
• Updatable views - Allow data manipulation
• Read only views - Do not allow data manipulation

TO CREATE THE TABLE 'FVIEWS'

SQL> create table fviews( name varchar2(20),no number(5), sal number(5), dno number(5));
Table created.
SQL> insert into fviews values('xxx',1,19000,11);
1 row created.
SQL> insert into fviews values('aaa',2,19000,12);
1 row created.
SQL> insert into fviews values('yyy',3,40000,13);
1 row created.
SQL> select * from fviews;

NAME NO SAL DNO

xxx 1 19000 11
aaa 2 19000 12
yyy 3 40000 13

TO CREATE THE TABLE 'DVIEWS'

SQL> create table dviews( dno number(5), dname varchar2(20));


Table created.
SQL> insert into dviews values(11,'x');
1 row created.
SQL> insert into dviews values(12,'y');
1 row created.
SQL> select * from dviews;
DNO DNAME
11 x
12 y

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV

CREATING THE VIEW 'SVIEW' ON 'FVIEWS' TABLE

SQL> create view sview as select name,no,sal,dno from fviews where dno=11;
View created.
SQL> select * from sview;

NAME NO SAL DNO


xxx 1 19000 11

Updates made on the view are reflected only on the table when the structure of the table and the view are
not similar -- proof
SQL> insert into sview values ('zzz',4,20000,14);
1 row created.
SQL> select * from sview;
NAME NO SAL DNO
xxx 1 19000 11
SQL> select * from fviews;
NAME NO SAL DNO

xxx 1 19000 11
aaa 2 19000 12
yyy 3 40000 13
zzz 4 20000 14

Updates made on the view are reflected on both the view and the table when the structure of the table and
the view are similar - proof

CREATING A VIEW 'IVIEW' FOR THE TABLE 'FVIEWS'


SQL> create view iview as select * from fviews;
View created.
SQL> select * from iview;
NAME NO SAL DNO
- -
xxx 1 19000 11
aaa 2 19000 12
yyy 3 40000 13
zzz 4 20000 14

PERFORMING UPDATE OPERATION


SQL> insert into iview values ('bbb',5,30000,15);
1 row created.

SQL> select * from iview;


NAME NO SALDNO

xxx 1 19000 11
bbb 5 30000 15

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
SQL> select * from fviews;
NAME NO SAL DNO
- -
xxx 1 19000 11
aaa 2 19000 12
yyy 3 40000 13
zzz 4 20000 14
bbb 5 30000 15

CREATE A NEW VIEW 'SSVIEW' AND DROP THE VIEW


SQL> create view ssview( cusname,id) as select name, no from fviews where dno=12;
View created.

SQL> select * from ssview;


CUSNAME ID

aaa 2

SQL> drop view ssview;


View dropped.

TO CREATE A VIEW 'COMBO' USING BOTH THE TABLES 'FVIEWS' AND 'DVIEWS'
SQL> create view combo as select name,no,sal,dviews.dno,dname from fviews,dviews where
fviews.dno=dviews.dno;
View created.
SQL> select * from combo;
NAME NO SAL DNO DNAME

xxx 1 19000 11 x
aaa 2 19000 12 y
TO PERFORM MANIPULATIONS ON THIS VIEW
SQL> insert into combo values('ccc',12,1000,13,'x');
insert into combo values('ccc',12,1000,13,'x')
*
ERROR at line 1:
ORA-01779: cannot modify a column which maps to a non key-preserved table
This shows that when a view is created from two different tables no manipulations can be performed using
that view and the above error is displayed.

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 anysystem user.
 The individual creating a public synonym does not own the synonym - rather, it will
belong to the PUBLIC user group that exists within Oracle.
 Private synonyms, on the other hand, belong to the system user that creates them and
reside in that user's schema.

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV

 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 SYNONYMprivilege.
 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;
Examples:
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

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV

ezhil 5
fairoz 7
hema 9
kalai 20
8 rows selected.
SQL> select * from c1;
NAME ID

anu 1
brindha 2
chinthiya 3
divya 4
ezhil 5
fairoz 7
hema 9
kalai 20
8 rows selected.
SQL> insert into class values('Manu',21);
1 row created.
SQL> select * from c1;
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.
SQL> select * from c1;
select * from c1
*
ERROR at line 1:
ORA-00942: table or view does not exist

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
Sequences

 Oracle provides the capability to generate sequences of unique numbers, and theyare
called sequences.
 Just like tables, views, indexes, 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 databasetables.
 The sequence of numbers can be generated in either ascending or descendingorder.

Creation of table:
SQL> create table class(name varchar(10),id number(10));
Table created.

Insert values into table:


SQL> insert into class values('&name',&id);
Enter value for name: anu
Enter value for id: 1
old 1: insert into class values('&name',&id)
new 1: insert into class values('anu',1)
1 row 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> 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.

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
SQL> insert into class values('divya',s_1.nextval);
1 row created.
SQL> select * from class;
NAME ID

anu 1
brindha 2
chinthiya 3
divya 4
Alter Sequence:
SQL> alter sequence s_1
2 increment by 2;
Sequence altered.
SQL> insert into class values('fairoz',s_1.nextval);
1 row created.
SQL> select * from class;
NAME ID

anu 1
brindha 2
chinthiya 3
divya 4
ezhil 5
fairoz 7
Drop Sequence:
SQL> drop sequence s_1;
Sequence dropped.
Indexes
 An index can be created in a table to find data more quickly and efficiently.
 The users cannot see the indexes; they are just used to speed up searches/queries.
 Updating a table with indexes takes more time than updating a table without; because the
indexes also need an update. So we should only create indexes on columns (and tables) that will
be frequently searched against.
Syntax:
Create Index:
CREATE INDEX index_name ON table_name (column_name)
SQL> create table splr(sname varchar(10),sid number(10),scity varchar(10));
Table created.
SQL> insert into splr values('hcl',01,'chennai');

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
1 row created.
SQL> insert into splr values('dell',04,'madurai');
1 row created.
SQL> insert into splr values('HP',02,'kovai');
1 row created.
SQL> insert into splr values('Lenovo',03,'trichy');
1 row created.

SQL> select * from splr;


SNAME SID SCITY

hcl 1 chennai
dell 4 madurai
HP 2 kovai
Lenovo 3 trichy
SQL> create index sp1 on splr(sid);
Index created.
SQL> create index sp2 on splr(sid,scity);
Index created. Drop Index:
SQL> drop index sp1;
Index dropped.
SQL> drop index sp2;
Index dropped.

RESULT:

Thus the Views, Synonyms, and Sequences has been executed using DDL, DML and DCL
statements.

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
EX.NO :4 DATABASE PROGRAMMING: IMPLICIT AND EXPLICIT
CURSORS

AIM To create a database for implementation of Implicit and Explicit Cursors.

Function with implicit Cursors:


Create a function for calculating the total marks and percentage of the student in a student management
system which uses a student table:

SQL> create or replace function stud_update


2 return number is
3 cursor c is select * from student;
4 ctot number
5 cper number
6 begin
7 for i in c
8 loop
9 ctot:=i.m1+i.m2+i.m3;
10 cper:=ctot/3;
11 update student set total=ctot where id_no=i.id_no;
12 update student set per=cper where id_no=id_no;
13 end loop;
14 Return 1;
15 End;
16 /
Function created

SQL> select * from student;

ID_NO NAME GR DE M1 M2 M3 TOTAL PER

10 Gouri a it 89 56 74 0 0

11 Akashaj s it 95 91 93 0 0

23 Lithik b bt 78 67 71 0 0

27 Pallavi s bt 90 98 96 0 0

30 Navaj a ph 88 81 89 0 0

SQL> declare
2 n number
3 begin
4 n:=stud_update;
5 end;
6/

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV

PL/sql Procedure successfully completed

SQL> select * from student

ID_NO NAME GR DE M1 M2 M3 TOTAL PER

10 Gouri a it 89 56 74 219 73

11 Akashaj s it 95 91 93 279 93

23 Lithik b bt 78 67 71 216 72

27 Pallavi s bt 90 98 96 284 94.6667


30 Navaj a ph 88 81 89 258 86

Function with explicit Cursors:

Creating a function for calculating net salary for all employees in an organization using an employee table

SQL> create or replace function salary


2 return number is
3 cursor c is select * from employee;
4 i employee%rowtype;
5 netsalary number;
6 begin
7 open c;
8 loop
9 fetch c into i;
10 If c%notfound then exit
11 end if
12 netsalary=i.basic+i.hra+i.da-i.pf;
13 update employee set netsal=netsalary where e_no=i.e_no;
14 end loop;
15 return netsalary;
16 close c;
17 end
18 /

SQL> select * from employee

E_NO E_NAME HRA DA PF BASIC NETSAL

100 Adithya 500 200 350 10000 0

101 Anusha 250 300 410 12000 0

102 Sara 250 300 100 20000 0

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV

103 Ragul 295 600 480 8500 0

104 Pooja 100 100 200 7500 0

Function created

SQL> declare
2 n number
3 begin
4 n:=salary;
5 end
6/

PL/SQL procedure successfully completed

SQL> select * from employee

E_NO E_NAME HRA DA PF BASIC NETSAL

100 Adithya 500 200 350 10000 10350

101 Anusha 250 300 410 12000 12140

102 Sara 250 300 100 20000 20450

103 Ragul 295 600 480 8500 8915


104 Pooja 100 100 200 7500 7500

RESULT:
Thus the database programming for implementing Implicit and Explicit Cursors has been executed and
verified.

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
EX.NO:5 PROCEDURES AND FUNCTIONS

AIM

To write PL/SQL programs that executes the concept of procedures and functions.

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
• Optional exception handling part
These procedures and functions do not show the errors.

KEYWORDS AND THEIR PURPOSES

 REPLACE: It recreates the procedure if it alreadyexists.


 PROCEDURE: It is the name of the procedure to be created.
 ARGUMENT: It is the name of the argument to the procedure. Parenthesis 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 defaultparameter.
 OUT: Specifies that the procedure passes a value for this argument back to it's calling environmentafter
 execution ie. used to return values to a caller of thesub-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 data typeof the function's return value because every function must return a value, this
clause is required.

PROCEDURES - SYNTAX
create or replace procedure <procedure name> (argument {in,out,inout} datatype ) {is,as}
variable declaration;
constant declaration;
begin
PL/SQL subprogram body;
exception
exception PL/SQL block; end;

CREATING THE TABLE 'ITITEMS' AND DISPLAYING THE CONTENTS

SQL> create table ititems(itemid number(3), actualprice number(5), ordid number(4), prodid number(4));
Table created.
SQL> insert into ititems values(101, 2000, 500, 201);
1 row created.
SQL> insert into ititems values(102, 3000, 1600, 202);
1 row created.
SQL> insert into ititems values(103, 4000, 600, 202);
1 row created.

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV

SQL> select * from ititems;


ITEMID ACTUALPRICE ORDID PRODID

101 2000 500 201


102 3000 1600 202
103 4000 600 202

PROGRAM FOR GENERAL PROCEDURE - SELECTED RECORD'S PRICE IS INCREMENTED


BY 500 , EXECUTING THE PROCEDURE CREATED AND DISPLAYING THE UPDATED TABLE

SQL> create procedure itsum(identity number, total number) is price number;


2 null_price exception;
3 begin
4 select actualprice into price from ititems where itemid=identity;
5 if price is null then
6 raise null_price;
7 else
8 update ititems set actualprice=actualprice+total where itemid=identity;
9 end if;
10 exception
11 when null_price then
12 dbms_output.put_line('price isnull');
13 end;
14 /
Procedure created.

SQL> exec itsum(101, 500);


PL/SQL procedure successfully completed

SQL> select * from ititems;


ITEMID ACTUALPRICE ORDID PRODID

101 2500 500 201


102 3000 1600 202
103 4000 600 202

PROCEDURE FOR 'IN' PARAMETER - CREATION, EXECUTION


SQL> set serveroutput on;
SQL> create procedure yyy (a IN number) is price number;
2 begin
3 select actualprice into price from ititems where itemid=a;
4 dbms_output.put_line('Actual price is ' || price);
5 if price is null then
6 dbms_output.put_line('price is null');
7 end if;
8 end;
9/
Procedure created.

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
SQL> exec yyy(103);
Actual price is 4000
PL/SQL procedure successfully completed.

PROCEDURE FOR 'OUT' PARAMETER - CREATION, EXECUTION


SQL> set serveroutput on;
SQL> create procedure zzz (a in number, b out number) is identity number;
2 begin
3 select ordid into identity from ititems where itemid=a;
4 if identity<1000 then
5 b:=100;
6 end if;
7 end;
8/
Procedure created.
SQL> declare
2 a number;
3 b number;
4 begin
5 zzz(101,b);
6 dbms_output.put_line('The value of b is '|| b);
7 end;
8/
The value of b is 100
PL/SQL procedure successfully completed.

PROCEDURE FOR 'INOUT' PARAMETER - CREATION, EXECUTION


SQL> create procedure itit ( a in out number) is
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/

The updated value is 8


PL/SQL procedure successfully completed.

FUNCTIONS - SYNTAX
create or replace function <function name> (argument in datatype,) return datatype {is,as}
variable declaration;
constant declaration;
begin

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
PL/SQL subprogram body;
exception
exception PL/SQL block;
end;

CREATE THE TABLE 'ITTRAIN' TO BE USED FOR FUNCTIONS

SQL>create table ittrain ( tno number(10), tfare number(10));


Table created.
SQL>insert into ittrain values (1001, 550);
1 row created.
SQL>insert into ittrain values (1002, 600);
1 row created.
SQL>select * from ittrain;
TNO TFARE
1001 550
1002 600

TO CREATE THE TABLE 'ITEMPLS'

SQL> create table itempls (ename varchar2(10), eid number(5), salary number(10));
Table created.
SQL> insert into itempls values('xxx',11,10000);
1 row created.
SQL> insert into itempls values('yyy',12,10500);
1 row created.
SQL> insert into itempls values('zzz',13,15500);
1 row created.

SQL> select * from itempls;

ENAME EID SALARY

xxx 11 10000
yyy 12 10500
zzz 13 15500

PROGRAM FOR FUNCTION AND IT'S EXECUTION


SQL> create function aaa (trainnumber number) return number is
2 trainfunction ittrain.tfare % type;
3 begin
4 select tfare into trainfunction from ittrain where tno=trainnumber;
5 return(trainfunction);
6 end;
7/

Function created.

SQL> set serveroutput on;


SQL> declare

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
2 total number;
3 begin
4 total:=aaa (1001);
5 dbms_output.put_line('Train fare is Rs. '||total);
6 end;
7/
Train fare is Rs.550
PL/SQL procedure successfully completed.

FACTORIAL OF A NUMBER USING FUNCTION — PROGRAM AND EXECUTION


SQL> create function itfact (a number) return number is
2 fact number:=1;
3 b number;
4 begin
5 b:=a;
6 while b>0
7 loop
8 fact:=fact*b;
9 b:=b-1;
10 end loop;
11 return(fact);
12 end;
13 /

Function created.

SQL> set serveroutput on;

SQL> declare
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

RESULT:
Thus the concept of procedure and function has been executed and verified.

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
EX.NO :6 TRIGGERS

AIM
To study and implement the concepts of triggers.

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 isassociated.
 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 securingauthorizations
• To maintain the replicatetable
• To audit data modifications
TYPES OF TRIGGERS
The various types of triggers are as follows,
• Before: It fires the trigger before executing the trigger statement.
• After: It fires the trigger after executing the trigger statement.
• 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.

VARIABLES USED IN TRIGGERS


 :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} on [tablename] [for each row/statement]
begin
exception
end;
USER DEFINED ERROR MESSAGE
The package "raise_application_error" is used to issue the user defined error messages
Syntax: raise_application_error(error number,'error message');
The error number can lie between -20000 and -20999.
The error message should be a character string.

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV

TO CREATE A SIMPLE TRIGGER THAT DOES NOT ALLOW INSERT UPDATE AND
DELETE OPERATIONS ON THE TABLE
SQL> create trigger ittrigg before insert or update or delete on itempls for each row
2 begin
3 raise_application_error(-20010,'You cannot do manipulation');
4 end;
5/
Trigger created.

SQL> insert into itempls values('aaa',14,34000);


insert into itempls values('aaa',14,34000)
*
ERROR at line1:
ORA-20010: You cannot do manipulation
ORA-06512: at "STUDENT.ITTRIGG", line 2
ORA-04088: error during execution of trigger 'STUDENT.ITTRIGG'

SQL> delete from itempls where ename='xxx';


delete from itempls where ename='xxx'
*
ERROR at line1:
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'

TO DROP THE CREATED TRIGGER


SQL> drop trigger ittrigg;
Trigger dropped.

TO CREATE A TRIGGER THAT RAISES AN USER DEFINED ERROR MESSAGE AND DOES
NOT ALLOW UPDATION AND INSERTION

SQL> create trigger ittriggs before insert or update of salary on itempls for each row
2 declare
3 triggsal itempls.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 /

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV

Trigger created.

SQL> insert into itempls values ('bbb',16,45000);


insert into itempls values ('bbb',16,45000)
*
ERROR at line1:
ORA-04098: trigger 'STUDENT.ITTRIGGS' is invalid and failed re-validation
SQL> update itempls set eid=18 where ename='zzz';
update itempls set eid=18 where ename='zzz'
*
ERROR at line 1:
ORA-04298: trigger 'STUDENT.ITTRIGGS' is invalid and failed re-validation

RESULT
Thus the triggers were created, executed and the outputs were verified.

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
EX.NO :7 EXCEPTION HANDLING

AIM:
To write a PL/SQL program with exception handling mechanisms.

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.
When an exception occurs amessages which explains its cause is recieved. PL/SQL Exception message
consists of three parts.
1) Type of Exception
2) An Error Code
3) A message

General Syntax for coding the exception section


DECLARE
Declaration section
BEGIN
Exception section
EXCEPTION
WHEN ex_name1 THEN
-Error handling statements
WHEN ex_name2 THEN
-Error handling statements
WHEN Others THEN
-Error handling statements
END;

Program with user defined exception:


SQL> DECLARE
2 N INTEGER:=&N;
3 A EXCEPTION; 4 B
EXCEPTION;
5 BEGIN
6 IF MOD(N,2)=0 THEN
7 RAISE A;
8 ELSE
9 RAISE B; 10 END IF;
11 EXCEPTION
12 WHEN A THEN
13 DBMS_OUTPUT.PUT_LINE('THE INPUT IS EVEN ')
14 WHEN B THEN
15 DBMS_OUTPUT.PUT_LINE('THE INPUT IS ODD ');
16 END;
17 /

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
Enter value for n: 20
old 2: N INTEGER:=&N; new 2: N INTEGER:=20; THE INPUT IS EVEN.....

PL/SQL procedure successfully completed.


SQL> /
Enter value for n: 21
old 2: N INTEGER:=&N; new 2: N INTEGER:=21;
THE INPUT IS ODD.....

PL/SQL procedure successfully completed.

Program with system defined exception:


Divide by zero exception:
SQL> DECLARE
2 L_NUM1 NUMBER;
3 L_NUM2 NUMBER;
4
5 BEGIN
6 L_NUM1 := 10;
7 L_NUM2 := 0;
8 DBMS_OUTPUT.PUT_LINE('RESULT:'||L_NUM1/L_NUM2);
9
10 EXCEPTION
11 WHEN ZERO_DIVIDE THEN
12 DBMS_OUTPUT.PUT_LINE(SQLCODE);
13 DBMS_OUTPUT.PUT_LINE(SQLERRM);
14
15 END;
16 /
-1476
ORA-01476: divisor is equal to zero

PL/SQL procedure successfully completed.

Handling the Exceptions on 'no data found'

SQL> create table employee1 (


2 id number,
3 employee_type_id number,
4 external_id varchar2(30),
5 first_name varchar2(30),
6 middle_name varchar2(30),
7 last_name varchar2(30),
8 name varchar2(100),
9 birth_date date ,
10 gender_id number );
Table created.

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV

SQL> create table gender (


2 id number,
3 code varchar2(30),
4 description varchar2(80),
5 active_date date default SYSDATE not null,
6 inactive_date date );

Table created.

SQL> insert into gender ( id, code, description ) values ( 1, 'F', 'Female');
1 row created.
SQL> insert into gender ( id, code, description ) values ( 2, 'M', 'Male');
1 row created.
SQL> insert into gender ( id, code, description ) values ( 3, 'U', 'Unknown');
1 row created.
SQL> set serveroutput on size 1000000;

SQL> declare
2
3 d_birth_date employee1.birth_date%TYPE;
4 n_gender_id employee1.gender_id%TYPE;
5 n_selected number := -1;
6 n_id employee1.id%TYPE;
7 v_first_name employee1.first_name%TYPE;
8 v_last_name employee1.last_name%TYPE;
9 v_middle_name employee1.middle_name%TYPE;
10 v_name employee1.name%TYPE;
11
12 begin
13 v_first_name := 'JOHN';
14 v_middle_name := 'J.';
15 v_last_name := 'DOUGH';
16 v_name := rtrim(v_last_name||', '||v_first_name||' '||v_middle_name);
17 d_birth_date := to_date('19800101', 'YYYYMMDD');
18
19 begin
20 select id into n_gender_id from gender where code = 'M';
21 exception
22 when OTHERS then
23 raise_application_error(-20001, SQLERRM||' on select gender');
24 end;
25
26 begin
27 select id
28 into n_id
29 from employee1

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
30 where name = v_name
31 andbirth_date =d_birth_date
32 and gender_id = n_gender_id;
33
34 n_selected := sql%rowcount;
35 exception
36 when NO_DATA_FOUND then
37 n_selected := sql%rowcount;
38 DBMS_OUTPUT.PUT_LINE('Caught raised exception NO_DATA_FOUND');
39 when OTHERSthen
40 raise_application_error(-20002, SQLERRM||' on select employee');
41 end;
42
43 DBMS_OUTPUT.PUT_LINE(to_char(n_selected)||' row(s) selected.');
44 end;
45/

Caught raised exception NO_DATA_FOUND

0 row(s) selected.
PL/SQL procedure successfully completed.

RESULT
Thus the PL/SQL program that handles exception has been implemented and output was verified.

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV

EX.NO :8 DATABASE DESIGN USING ER MODELING, NORMALIZATION AND


IMPLEMENTATION FOR ANY APPLICATION
Aim:
To design a ER modeling, normalization and to implement for real time application.

Entity-Relationship Diagram – BANK MANAGEMENT SYSTEM

RESULT:
Thus the ER Database design using E-R model and Normalization was implemented successfully.

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
EX.NO :9 DATABASE CONNECTIVITY WITH FRONT END TOOLS

FRONT END FOR DBMS - VISUAL BASIC 6.0

The Development Environment

Learning the ins and outs of the Development Environment before you learn visual basic is somewhat like
learning for a test you must know where all the functions belong and what their purpose is. First we will start
with labeling the development environment.

The above diagram shows the development environment with all the important points labeled. Many of Visual
basic functions work similar to Microsoft word eg the Tool Bar and the tool box is similar to other products on
the market which work off a single click then drag the width of the object required. The Tool Box contains the
control you placed on the form window. All of the controls that appear on the Tool Box controls on the above
picture never runs out of controls as soon as you place one on the form another awaits you on the Tool Box
ready to be placed as needed.

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
The project explorer window

The Project explorer window gives you a tree-structured view of all the files inserted into the application. You
can expand these and collapse branches of the views to get more or less detail (Project explorer). The project
explorer window displays forms, modules or other separators which are supported by the visual basic like
class'es and Advanced Modules. If you want to select a form on its own simply double click on the project
explorer window for a more detailed look. And it will display it where the Default form is located.

Properties Window

Some programmers prefer the Categorisized view of the properties window. By defaulting, the properties
window displays its properties alphabetically (with the exception of the name value) when you click on the
categorized button the window changes to left picture.

The Default Layout

When we start Visual Basic, we are provided with a VB project. A VB project is a collection of the following
modules and files.

 The global module( that contains declaration and procedures)


 The form module(that contains the graphic elements of the VB application along with the instruction )
 The general module (that generally contains general-purpose instructions not pertaining to anything
graphic on-screen)
 The class module(that contains the defining characteristics of a class, including its properties and methods)
 The resource files(that allows you to collect all of the texts and bitmaps for an application in one place)

On start up, Visual Basic will displays the following windows :

1. The Blank Form window


2. The Project window
3. The Properties window

It also includes a Toolbox that consists of all the controls essential for developing a VB Application. Controls
are tools such as boxes, buttons, labels and other objects draw on a form to get input or display output. They
also add visual appeal.

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
Understanding the tool box.

You may have noticed that when


you click on different controls the
Properties Window changes
slightly this is due to different
controls having different functions.
Therefore more options are needed
for example if you had a picture
then you want to show an image.
But if you wanted to open a internet
connection you would have to fill in
the remote host and other such
settings. When you use the
command ( ) you will find that a
new set of properties come up the
following will provide a description
and a property.

Opening an existing Visual Basic project.

Microsoft have included some freebies with visual basic to show its capabilities and functions. Dismantling or
modifying these sample projects is a good way to understand what is happening at runtime. These files can be
located at your default directory /SAMPLES/
To Open these projects choose 'Open Project' from the 'File' menu. Then Double click on the samples folder to
open the directory then Double click on any project to load it.

Opening a new visual basic file & Inserting Source code.

From looking at the examples it time to make your own application. Choose 'New Project' from the 'File' menu.
Use the blank form1 to design a simple interface for an estate agents database, have some textboxes for names
and other details. Insert some controls and make it look professional. Textboxes can be used to store there name
and other details, make sure you put a picture box in for a picture of the house.
Now insert the following source code for your application.
Private Sub Form_Load()
Picture1.Picture = LoadPicture("C:\Program Files\VB\Graphics\Icons\Misc\MISC42.ICO")
End Sub

Running and viewing the project in detail.

Once an application is loaded it can be run by click on the icon from the toolbar, to pause press and to

terminate use . Once a project is loaded, the name of the form(s) that it contains is displayed in the project
window. To view a form in design mode, select the form required by clicking with the mouse to highlight its
name, then clicking on the view form button.

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV

In this example the project has been loaded and the maillist.frm has been selected for viewing. This Ms Mail
example project useds 6 forms and 1 modules.

In Design mode, when the form is viewed, the code attached to any screen object may be inspected by double
clicking on that object. The screen shots below show the interface of the Ms Mail example
(.../samples/Comtool/VBMail/MaiLLST.FRM) to view the code for this form select from the project window
item.

Private Sub SetupOptionForm(BasePic As Control)

BasePic.Top = 0
BasePic.Left = 0
BasePic.Visible = True
BasePic.enabled = True
OKBt.Top = BasePic.Height + 120
Me.width = BasePic.Width + 120
Me.Heigh = OkBt.Top + OkBt.Height + 495

End Sub
Brief introduction to the usages of Access data bases

The most compelling thing about Visual Basic is it's easy way of accessing and modifying databases. There are
many ways to work with databases in Visual Basic, and Use in this text is DAO (Data Access Objects). We will
get familiar with opening a database and retrieving/adding/deleting/updating records from tables. Use an Access
Database (*.mdb) in examples, since this is the most used DBMS (DataBase Management System) for smaller
applications made in Visual Basic. We will at the end of this lesson have made a simple, yet functional, phone
book application.

Database Object

The first thing you must do in your application is to open a database where your tables are stored. You need to
declare a variable to hold your database in order to do this. This is done with:

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV

Dim dbMyDB As Database

This gives you a variable/object that can hold a reference to your database. To open a simple Access database
named "MyDatabase.mdb", do this:

Set dbMyDB = OpenDatabase("MyDatabase.mdb")


So, now you have opened a database. This won't give you any data. What you need to do is open a table in the
database. You're not limited to open a single table; sometimes you have two or more tables that are related to
each other and linked together w ith foreign keys, and there are ways to handle this to. But in this "Visual Basic -
Database Primer”

RecordSet Object

Visual Basic uses an object called RecordSet to hold your table. To declare such an object and to open the table,
do this:

Dim rsMyRS As RecordSet

Set rsMyRS = dbMyDB.OpenRecordSet("MyTable", dbOpenDynaset)


Declared a RecordSet object and used the Database object's OpenRecordSet method to open a table of type
Dynaset. Open a RecordSet in several modes. VB's online help file explains the different modes and what they
are for. The Dynaset mode is the mode I use mostly. It gives you a RecordSet that you can add, delete and
modify records in.

Accessing records

Now that we have opened a table (referred to as RecordSet from now on) we want to access the records in it. The
RecordSet object allows us to move in it by using the methods MoveFirst, MoveNext, MovePrevious, MoveLast
(among others). I will use some of these to fill up a list box with the records of our RecordSet.

To get this example to work, make a database (with Access) called "MyDatabase.mdb" with the table "MyTable"
in it. This table should have the fields "ID" of type "Counter" that you set to be the primary key, the field
"Name" of type Text and a field "P hone" of type Text. Add some records to it. Put a list box on a form and call
it "lstRecords".

Dim dbMyDB As Database


Dim rsMyRS As RecordSet
Private Sub Form_Load()
Set dbMyDB = OpenDatabase("MyDatabase.mdb")
Set rsMyRS = dbMyDB.OpenRecordSet("MyTable", dbOpenDynaset)

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
If Not rsMyRS.EOF Then rsMyRS.MoveFirst
Do While Not rsMyRS.EOF
lstRecords.AddItem rsMyRS!Name
lstRecords.ItemData(lstRecords.NewIndex) = rsMyRS!ID
rsMyRS.MoveNext
Loop
End Sub

This will make the list box fill up with your records when the form loads. The line that says If Not rsMyRS.EOF
Then rsMyRS.M oveFirst tells the program to move to the first record in case there are any records at all. The
EOF is a Boolean property that is true if the current record is the last. It is also true if there are no records in the
RecordSet.

Then we make the program add the "Name" field of all records to the list box by adding the current records field
"Name" and moving to the next record. You ask for a field of a RecordSet by putting a ! between the name of the
RecordSet object and the na me of the field. The while loop checks to see if there are more records to add.

Searching the RecordSet

The primary key for all the records in order to search for a record.

Put a text box somewhere on the form and call it "txtPhone". Then copy the following code to the project.

Private Sub lstRecords_Click()


rsMyRS.FindFirst "ID=" & Str(lstRecords.ItemData(lstRecords.ListIndex))
txtPhone.Text = rsMyRS!Phone
End Sub
This will display the phone number of the selected person when clicking in the list box. It uses the FindFirst
method of the RecordSet object. This takes a string parameter that is like what is after WHERE in a SQL
expression. You state the field that you want to search in (here "ID"), then the evaluation criteria (here "=") and
last the value to search for (here the ItemData of the selected item in the list box).

So what we did was to search for the record with the "ID" field value that was the same as the ItemData property
of the selected item in the list box. Then we show the value of the "Phone" field in the text box.

Updating the Database

You will probably want to be able to update some value of some field when doing database programming. This
is done with Edit and Update. We will try to change the value of the "Phone" field by editing the text in the text
box and clicking a button.

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
Put a command button on the form and name it "cmdUpdate". Then copy the following code to the project.

Private Sub cmdUpdate_Click()


rsMyRS.Edit
rsMyRS!Phone = txtPhone.Text
rsMyRS.Update
End Sub
Could it be that simple? Yes. This changes the phone number of our selected person. Or to put it technically:
This changes the value of the "Phone" field of our current record. Imagine the current record being a set of
boxes, with a field in each box. The Edit method takes the lid off all of the boxes and Update puts them back on.
When we write rsMyRS!Phone = txtPhone.Text we replace the content of the "Phone" box with the content in
the text box.

Deleting and Adding records

Deleting

Deleting records couldn't be simpler. To delete the current record you just invoke the Delete method of the
RecordSet object. We will put this feature in our little project. Make one more command button named
"cmdDelete" and the following code will do the work of deleting our currently selected person.

Private Sub cmdDelete_Click()


The
rsMyRS.Delete first
lstRecords.RemoveItem lstRecords.ListIndex

End Sub
statement deletes the record and the second removes the list box entry.

Adding

Adding records is much like updating, except you use AddNew instead of Edit. Let's add one more command
button to our application. Let's call it...errh...let me see...yea! "cmdNew" =). Here is the code that adds a new
record.

Private Sub cmdNew_Click()

rsMyRS.AddNew
rsMyRS!Name = "A New Person"
lstRecords.AddItem rsMyRS!Name
lstRecords.ItemData(lstRecords.NewIndex) = rsMyRS!ID
rsMyRS!Phone = "Person's Phone Number"

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
rsMyRS.Update

End Sub

The AddNew method takes a set of new boxes and adds them to our RecordSet. We then put some new values in
them and close the lids with Update. As you can see we never stated any value for "ID", but as you remember,
this is a field of type "Counter" which automatically gets a unique value. The code also adds this new record to
the list box so that we will be able to change the phone number of this person. I leave it up to you to add the
feature of changing the name.

RESULT
Thus the database connectivity using front end tools has been implemented successfully.

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
EX.NO:10 CASE STUDY USING REAL LIFE DATABASE APPLICATIONS

DESIGN AND IMPLEMENTATION OF BANK MANAGEMENT SYSTEM

Aim:

To develop a banking application using visual basic as front end and ORACLE as back end .

Module:

Bank details

Form1: Bank

Name Null? Type

ACC NO NUMBER(3)

NAME VARCHAR2(10)

OCCUPATION VARCHAR2(10)

BALANCE NUMBER(6)

PHNO NUMBER(6)

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
FORM DESIGN:

Coding:
Dim con As New ADODB.Connection
Dim rs As New ADODB.Recordset
Sub clear()
Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
Text4.Text = ""
Text5.Text = ""
End Sub
Sub display()
Text1.Text = rs(0)
Text2.Text = rs(1)

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
Text3.Text = rs(2)
Text4.Text = rs(3)
Text5.Text = rs(4)
End Sub

Private Sub Command5_Click()


End
End Sub

Private Sub add_Click()


clear
Text1.SetFocus
End Sub

Private Sub delete_Click()


rs.delete
MsgBox "record deleted"
rs.MoveNext
display
End Sub

Private Sub deposit_Click()


Dim w As Integer
w = InputBox("enter the Deposit Amount")
Text4.Text = Val(Text4.Text) + w
MsgBox (Text4.Text)
rs(3) = Text4.Text
rs.update
MsgBox "record updated"
Text1.SetFocus
End Sub

Private Sub exit_Click()


End
End Sub

Private Sub find_Click()


Dim w As Integer
w = InputBox("enter the employee number")

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
On Error GoTo er
rs.find "accno=" & w, , adSearchForward
display
Exit Sub
er:
clear
MsgBox "record not found"
End Sub

Private Sub first_Click()


rs.MoveFirst
display
End Sub

Private Sub Form_Load()


con.Open "e", "scott", "tiger"
rs.Open "select * from newmember", con, adOpenDynamic, adLockPessimistic
rs.MoveFirst
End Sub

Private Sub last_Click()


rs.MoveLast
display
End Sub

Private Sub modify_Click()


rs(0) = Text1.Text
rs(1) = Text2.Text
rs(2) = Text3.Text
rs(3) = Text4.Text
rs(4) = Text5.Text
rs.update
MsgBox "record modified"
End Sub
Private Sub next_Click()
rs.MoveLast
If rs.EOF = True Then
rs.MoveFirst
display

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
Else
display
End If
End Sub

Private Sub previous_Click()


rs.MovePrevious
If rs.BOF = True Then
rs.MoveLast
display
Else
display
End If
End Sub

Private Sub update_Click()


rs.MoveLast
rs.AddNew
rs(0) = Text1.Text
rs(1) = Text2.Text
rs(2) = Text3.Text
rs(3) = Text4.Text
rs(4) = Text5.Text
rs.update
display
MsgBox "Record updated"
clear
End Sub

Private Sub withdrawal_Click()


Dim w As Integer
w = InputBox("enter the Withdrawal Amount")
Text4.Text = Val(Text4.Text) - w
rs(3) = Text4.Text
rs.update
MsgBox "record updated"
End Sub

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
Output screen shots:

Save

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
Find

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
Modify

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV

Delete

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV
Deposit

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV

Withdrawal

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering
Sub. Code: 20CS4L1 Year: II
Sub. Name: Database Management Systems Laboratory Semester: IV

Department of ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


K.L.N College of Engineering

You might also like