DBMS Lab Manual
DBMS Lab Manual
PREPARED BY
Mr.B.Anandasabarirajan, BE,ME
SYLLABUS
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.
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
DDL statements
DDL COMMANDS
SQL> create table stud (sname varchar2(30), sid varchar2(10), sage number(2), sarea varchar2(20));
Table created.
DML statements
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
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.
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.
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.
CONCATENATION OPERATOR
SQL> select sname || ' is a ' || sdept || ' engineer. ' AS "PROFESSION" from studs;
PROFESSION
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
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 OR OPERATOR
SQL> select sname ,sid from studs where sid>102 or sarea='anna nagar';
SNAME SID
Ashwin 101
Pruthvik 103
charith 104
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
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^^^^
CONVERSION FUNCTIONS
SQL> update studs set sage=to_number(substr(118,2,3));
4 rows updated.
SYSDATE RESULT
16-JUL-08 16-NOV-08
SYSDATE RESULT
16-JUL-08 20-JUL-08
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
table 10001
chair 10010
desk 10110
cot 11110
sofa 10010
tvstand 11010
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
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.
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
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.
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
SQL> create table sstud2 ( sname varchar2(20), dept varchar2(10), marks number(10));
Table created.
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
SQL> select sname from sstud1 where not exists ( select sstud2.sname from sstud2 where
sstud1.sname=sstud2.sname );
SNAME
kumar
10 inventory hyd
20 finance bglr
30 HR mumbai
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
4. Natural Join:
It compares all the common columns.
5. Cross Join:
This will give the cross product.
SQL> select eno,ename,job,dname,loc from emp2 cross join dept;
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(+);
RESULT
The Simple queries, Nested queries, Sub queries and Joins using DML commands were executed
and the output was verified.
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
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;
xxx 1 19000 11
aaa 2 19000 12
yyy 3 40000 13
SQL> create view sview as select name,no,sal,dno from fviews where dno=11;
View created.
SQL> select * from sview;
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
xxx 1 19000 11
bbb 5 30000 15
aaa 2
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.
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
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
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.
anu 1
brindha 2
chinthiya 3
Create Sequence:
SQL> create sequence s_1
2 start with 4
3 increment by 1 4 maxvalue 100
5 cycle;
Sequence created.
anu 1
brindha 2
chinthiya 3
divya 4
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');
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.
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/
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
Creating a function for calculating net salary for all employees in an organization using an employee table
Function created
SQL> declare
2 n number
3 begin
4 n:=salary;
5 end
6/
RESULT:
Thus the database programming for implementing Implicit and Explicit Cursors has been executed and
verified.
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.
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;
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.
SQL> declare
2 a number:=7;
3 begin
4 itit(a);
5 dbms_output.put_line('The updated value is '||a);
6 end;
7/
FUNCTIONS - SYNTAX
create or replace function <function name> (argument in datatype,) return datatype {is,as}
variable declaration;
constant declaration;
begin
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.
xxx 11 10000
yyy 12 10500
zzz 13 15500
Function created.
Function created.
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.
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.
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.
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.
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 /
Trigger created.
RESULT
Thus the triggers were created, executed and the outputs were verified.
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
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
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.
RESULT:
Thus the ER Database design using E-R model and Normalization was implemented successfully.
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.
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.
When we start Visual Basic, we are provided with a VB project. A VB project is a collection of the following
modules and files.
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.
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.
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
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.
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.
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:
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:
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:
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".
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.
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.
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.
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.
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.
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.
rsMyRS.AddNew
rsMyRS!Name = "A New Person"
lstRecords.AddItem rsMyRS!Name
lstRecords.ItemData(lstRecords.NewIndex) = rsMyRS!ID
rsMyRS!Phone = "Person's Phone Number"
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.
Aim:
To develop a banking application using visual basic as front end and ORACLE as back end .
Module:
Bank details
Form1: Bank
ACC NO NUMBER(3)
NAME VARCHAR2(10)
OCCUPATION VARCHAR2(10)
BALANCE NUMBER(6)
PHNO NUMBER(6)
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)
Save
Delete
Withdrawal