Professional Documents
Culture Documents
DBMSLAB
DBMSLAB
No:1a
Date: DATA DEFINITION LANGUAGE (DDL)
COMMANDS IN RDBMS
AIM:
To study and execute the Data Definition Language (DDL) in RDBMS.
DDL QUERIES:
1. CREATE COMMAND:
This command is used to create the table.
Syntax:
Create table tablename(columnname datatype(size));
2. ALTER COMMAND:
This is used for adding the values and also modifying the table.
Syntax:
Alter table tablename add or modify(columnname datatype(size);
3. DESC COMMAND:
This command is used to give the structure of the table.
Syntax:
desc tablename;
4. TRUNCATE COMMAND:
The contents of the table are deleted by using this command.
Syntax:
truncate table tablename
5. DROP COMMAND:
This command is used to delete the entire table.
Syntax:
drop table tablename
Sample Output:
CREATE COMMAND:
Table created.
1
ALTER (ADD) COMMAND:
Table altered.
Table altered.
TRUNCATE COMMAND:
Table truncated.
DROP COMMAND:
Table dropped.
Result:
Thus the basic Data Definition Commands are executed and verified successfully.
2
Ex.No:1b
Date: DML AND DCL COMMANDS IN RDBMS
AIM:
DML COMMANDS:
1. CREATE COMMAND
It is used to create the new table.
Syntax:
Create table table name (field name data type (size));
2. INSERT COMMAND
It is used to insert the values into table.
Syntax:
insert into tablename values (‘&fieldname’….);
Or
insert into tablename values (field1,field2….);
3. UPDATE COMMAND
Used to update the table values when new values are added .
Syntax:
update tablename set fieldname=value;
4. DELETE COMMAND:
Deleting the new which contain the values.
Syntax:
delete from tablename where fieldname=value;
5. SELECT COMMAND:
This command is used to view the record in the table.
Syntax:
select * from tablename
DCL COMMANDS:
1. COMMIT:
To make all transaction changes permanent to the database.
Syntax: commit.
2. ROLLBACK COMMAND:
Used to undo the last performed operation.
Syntax: Rollback;
3.GRANT COMMAND:
Used to grant permission to perform mentioned operations.
Syntax:
grant select insert,update,delete on tablename to public;
3
4.REVOKE COMMAND:
Used to cancel the permission provided by grant operations.
Syntax:
revoke select insert,update,delete on tablename from public;
Sample Output:
CREATE COMMAND:
Table created.
INSERT COMMAND:
1 row created.
SQL> /
Enter value for sname: keerthi
Enter value for rno: 106
Enter value for course: it
Enter value for fees: 50000
old 1: insert into dml values('&sname',&rno,'&course',&fees)
new 1: insert into dml values('keerthi',106,'it',50000)
1 row created.
SQL> /
Enter value for sname: ramu
Enter value for rno: 107
Enter value for course: cse
Enter value for fees: 40000
4
old 1: insert into dml values('&sname',&rno,'&course',&fees)
new 1: insert into dml values('ramu',107,'cse',40000)
1 row created.
SQL> /
Enter value for sname: rini
Enter value for rno: 108
Enter value for course: eee
Enter value for fees: 50000
old 1: insert into dml values('&sname',&rno,'&course',&fees)
new 1: insert into dml values('rini',108,'eee',50000)
1 row created.
ALTER COMMAND:
Table altered.
UPDATE COMMAND:
2 rows updated.
DELETE COMMAND:
5
1 row deleted.
COMMIT COMMAND:
SQL> commit;
Commit complete.
ROLLBACK COMMAND:
SQL> rollback;
Rollback complete.
1 row deleted.
6
SNAME RNO COURSE FEES ADDRESS
--------------- ---------- --------- ---------- -------------
keerthi 106 it 50000
ramu 107 cse 60000
SQL> rollback;
Rollback complete.
GRANT COMMAND:
Types of Privilege:
Permission granted to execute the various data definition command like Create Table,
Create Sequence, create session are called System Privilege.
Granting System Privilege:
Grant Command is used to give System Privilege to an oracle user.
Syntax:
GRANT system privilege TO user
Grant succeeded.
TO CHECK:
1 row deleted.
7
An Object Privilege enables a user to execute some commands on the database object like
table view sequence etc. Some of the object privileges are
i. Alter
ii. Index
iii. Insert
iv. Update
v. Delete
vi. Select
vii. References
Syntax:
Grant object privilege [Object privilege] ON object to user [with grant option]
Example:
SQL> Grant Create session to student;
SQL> Grant create table to student;
SQL> Connect student/young;
SQL> Connect system/managers;
SQL> Create user staff identified by guru;
SQL> Grant resource to staff;
SQL> Connect staff/guru;
SQL> Select * from staff;
Staff master in a table in the user staff we first log on the staff
[SQL> Connect staff/guru;]
SQL> Grant select insert on staff master to student;
Now log on to student and try the select command
SQL> Connect student/young;
SQL> Select * from staff;
In this manner user can verify the following example:-
1. SQL> Grant select, update, delete on student-master to staff;
REVOKE COMMAND:
Revoking the permission:
8
Permission granted to a user can also be taken back by the granter. This can be done by
the REVOKE command.
Syntax:
Revoke object privilege [object privilege] ON object name from user name;
Example:
i. SQL> REVOKE SELECT, INSERT ON STUDENT_MASTER from staff;
ii. SQL> REVOKE SELECT ON STUDENT_MASTER from rajan;
Revoke succeeded.
RESULT:
Thus the basic DML, DCL and TCL commands are successfully executed and the output
is verified.
9
Savepoint id;
2. ROLLBACK:
Rollback commands undo all the changes made in the current transaction.
Syntax:
a. Rollback
b. Rollback to Save point id1;
The first one will rollback (undo) the entire transaction and the last one will undo all
changes
made after the creation of the save point id1.
RESULT:
Thus the basic TCL commands are successfully executed and the output is verified.
Subquery
A subquery is a query within a query. Sub queries are also known as nested queries and are
used to answer multi-part questions. These subqueries can reside in the WHERE clause,
the FROM clause, or the SELECT clause. Sub queries and joins are often interchangeable
and in fact the Oracle optimiser may well treat a query containing a sub-query exactly as
if it were a join.
Let's use a trivial example of finding the names of everybody who studies in the same
branch as a person called NANDAKUMARAN to illustrate this point. The SQL could be
written using a sub query as follows:
SELECT name FROM student WHERE branchno = (SELECT branchno FROM
student WHERE name = 'NANDAKUMARAN');
or as a join statement, like this:-
SELECT s1.name FROM student s1, student s2
WHERE s1.branchno = s2.branchno AND s2.name = 'NANDAKUMARAN';
With a trivial example like this there would probably be very little difference in terms of
10
performance of the SQL for such a simple query, but with more complex queries there
could well be performance implications.
1. SELECT
Example: select name from cust;
Output: NAME
hayes
jones
blake
2. WHERE
Example: select city from cust where name= “hayes”;
Output: CITY
harrison
3. FROM
Example: select name, city from cust;
Output: NAME CITY
hayes harrison
jones redwood
blake downtown
britto mounthill
smith harrison
4. RENAME
Example: select borrower.loan_no as loan_id from borrower;
Output: LOAN_ID
16
93
15
14
17
5. STRING OPERATIONS
(a) “%”.
11
Example: select name from cust where city like ’har%’;
Output: NAME
hayes
smith
(b) “_”.
Example: select city from cust where name like “_ _ _ _ _”;
Output: CITY
harrison
redwood
downtown
harrison
6. ORDERING OF TUPLES
Example: select * from loan order by amount asc;
Output: LOAN NO BRANCH AMOUNT
7. UNION
11 roundhill 900
16 perryridge 1100
14 downtown 1500
15 perryridge 1500
17 redwood 2000
Example: (select name from depositor) union (select name from borrower);
Output: NAME
adams
britto
hayes
jones
smith
8. INTERSECTION
Example: (select name from depositor) intersect (select name from borrower);
Output: NAME
12
hayes
jones
9. AGGREGATE FUNCTIONS
(a) AVERAGE.
Example: select avg (balance) from account;
Output: AVG (BALANCE)
487.5
(b) MINIMUM.
Example: select min (balance) from account;
Output: MIN (BALANCE)
350
(c) MAXIMUM.
Example: select max (balance) from account;
Output: MAX (BALANCE)
700
(d) TOTAL.
Example: select total (balance) from account;
Output: SUM (BALANCE)
1950
(e) COUNT.
Example: select count (balance) from account;
Output: COUNT (BALANCE)
4
10. NESTED QUERIES
Example: select name from depositor where depositor.name in (select name from
cust);
Output: NAME
hayes
jones
13
NESTED QUERIES
Aim:
To execute the nested queries
Table structure:
SQL>desc emp_det;
SQL>desc pro_det;
SQL>desc work_in;
Sample Output:
7 rows selected
3 rows selected
Output:
4 rows selected
Join:
A join is used to combine rows from multiple tables. A join is performed whenever
two or more tables are listed in the form clause of an SQL statement.
Table structure:
SQL>desc suppliers;
Name NULL? Type
------ --------- --------- -----------------
Supplier_id number(5)
Supplier_name varchar2(25)
SQL>desc order;
Supplier:
Supid supname
------- ------ --------- ------
12 abi
13 chindu
14 nithi
15
15 selvi
Order:
Oid supid odate
------- ------- ---------- ------- --------- -------
111 12 1/9/09
222 23 8/9/09
333 14 6/9/09
444 25 3/9/09
555 15 17/9/09
01. Natural joins:
Output:
Supid supname Oid supid odate
-------- ---------- ----------- --------------- ------------- ---------- ------
12 abi 111 12 1/9/09
14 nithi 333 14 6/9/09
15 selvi 555 15 17/9/09
02.Outer Join:
Output:
SuPID SuPNAME Odate
--------- --------- --------- --------- -------- ----------
12 abi 1/9/09
14 nithi 6/9/09
15 selvi 17/9/09
8/9/09
3/9/09
Output:
16
Full outer join:
Sample Output:
01.Find the names of all employees who do work in department where geetha is
working.
SQL>select ename from emp_det where dno not in (select dno from emp_det where
ename = ‘geetha’);
Output:
ENAME
------ ------
Abi
Deepak
Anjali
Kiruthi
Chindu
4 rows selected
02. Find names of employees who are working in the same department with Shirley.
SQL>select ename,dno from emp_det where dno=(select dno from emp_det where
ename=’shirley’)order by ename;
Output:
ENAME DNO
--------------- ---------------
Geetha 3
Shirley 3
2 rows selected
03. Find the names of employees who are working in DBMS project.
17
SQL>select ename from emp_det where eno in(select eno from work_in where
pno=(select pno from pro_det where pname=’DBMS’))order by ename
Output:
ENAME
---- -------
Abi
Deepak
2 rows selected
04. Find names and basic salary of those employees of the department with dno2
who get more salary the highest paid employee of the department with dno 10.
SQL>select ename,basic_salary from emp_det where dno = 2 and basic_salary > (select
max(basic_salary)from emp_det where dno=10)order by ename;
Output:
ENAME BASIC_SALARY
---------------- ------------------ ---------------- --------------------------
Anjali 10000
Kiruthi 10000
2 rows selected
Output:
ENAME JOB_STATUS BASIC_SALARY
---------------- ------------------ ---------------- --------------------------
Chindu professor 7800
1 row selected
06. Find the names of all projects in which employees are working.
SQL>select pno,pname from pro_det where exists(select pno from work_in where
work_in.pno=pro_det.pno)
Output:
PNO PNAME
1 DBMS
2 COMPILER
2 rows selected
18
SQL>select * from emp_det where basic_salary=(select max(basic_salary)from
emp_det);
Output:
ENO ENAME ADDRESS BASIC_SALARY JOB_STAUS DNO
--------- ---------- ------------ ------------ ------------ ------- ------------ -------------
3 anjali raj street 10000 assistant 2
6 kiruthi kovai 10000 professor 2
2 rows selected
Output:
MAX(BASIC_SALARY)
----------- ----------------------
8500
09. List the salary where basic is less than the average salary.
Output:
RESULT:
Thus, the queries and joins in SQL were executed and the outputs were verified.
19
Ex.No:4
Date: VIEWS
Introduction:
View as a lens looking at one or more tables. A view is really nothing more than a
logical representation of one or more tables in a database. View offer the following
benefits and functionality.
Can hide certain columns in a table. For example you may want to allow employees
to see other employees to see the phone number column, but only certain employees
to be able to access an employees salary column!
Can provide huge time savings in writing queries by already having a group of
frequently accessed tables joined together in a view.
Views allow you to use functions and manipulate data in ways that meet your
requirements. For example, you store a persons birth date, but you like to calculate
this to determine their age.
Views
(i) Logically represents subsets of data from one or more tables.
(ii) You can present logical subsets or combinations of data by creating views of
tables. A view
is a logical table based on a table or another view. A view contains no data of its own
but is like
a window through which data from tables can be viewed or changed. The tables on
which a view
is based are called base tables. The view is stored as a SELECT statement in the data
dictionary.
Why Use Views?
• To restrict data access
• To make complex queries easy
• To provide data independence
• To present different views of the same data.
Advantages of Views
• Views restrict access to the data because the view can display selective columns
from the table.
20
• Views can be used to make simple queries to retrieve the results of complicated
queries. For
example, views can be used to query information from multiple tables without the
user knowing
how to write a join statement.
• Views provide data independence for ad hoc users and application programs. One
view can be
used to retrieve data from several tables.
• Views provide groups of users access to data according to their particular criteria.
Simple Views versus Complex Views
There are two classifications for views: simple and complex. The basic difference is
related to
the DML (INSERT, UPDATE, and DELETE) operations.
• A simple view is one that:
– Derives data from only one table
– Contains no functions or groups of data
– Can perform DML operations through the view
• A complex view is one that:
– Derives data from many tables
– Contains functions or groups of data
– Does not always allow DML operations through the view
Creating a View
• You embed a subquery within the CREATE VIEW
statement.
Syntax:
CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view
[(alias[, alias]...)] AS subquery
[WITH CHECK OPTION [CONSTRAINT constraint]]
[WITH READ ONLY [CONSTRAINT constraint]];
– • The subquery can contain complex SELECT
Example:
• Create a view, EMPVU80, that contains details of
21
employees in department 80.
CREATE VIEW empvu80
AS SELECT employee_id, last_name, salary
FROM employees
WHERE department_id = 80;
View created.
• Describe the structure of the view by using the iSQL*Plus DESCRIBE
command.
Example:
DESCRIBE empvu80
Assigning Names to Columns
We Can Assign names for the various colmns in the view.
* Create a view by using column aliases in the
subquery.
CREATE VIEW salvu50
AS SELECT employee_id ID_NUMBER, last_name NAME,
salary*12 ANN_SALARY
FROM employees
WHERE department_id = 50;
View created.
(or)
CREATE VIEW salvu50(ID_NUMBER,NAME,ANN_SALARY)
AS SELECT employee_id , last_name ,
salary*12
FROM employees
WHERE department_id = 50;
View created.
• Select the columns from this view by the given alias names.
Retrieving Data from a View
SELECT * FROM salvu50;
22
Modifying a View
• Modify the EMPVU80 view by using CREATE OR REPLACE VIEW clause. Add
an alias for
each column name.
• Column aliases in the CREATE VIEW clause are listed in the same order as the
columns in the
subquery.
CREATE OR REPLACE VIEW empvu80
(id_number, name, sal, department_id)
AS SELECT employee_id, first_name || ’ ’ || last_name,
salary, department_id
FROM employees
WHERE department_id = 80;
View created.
Creating a Complex View
Create a complex view that contains group functions to display values from two
tables.
CREATE VIEW dept_sum_vu
(name, minsal, maxsal, avgsal)
AS SELECT d.department_name, MIN(e.salary),
MAX(e.salary),AVG(e.salary)
FROM employees e, departments d
WHERE e.department_id = d.department_id
GROUP BY d.department_name;
View Created;
Creating a Complex View
The example on the slide creates a complex view of department names, minimum
salaries, maximum salaries, and average salaries by department. Note that alternative
23
names have been specified for the view. This is a requirement if any column of the
view is derived from a function or an expression. You can view the structure of the
view by using the iSQL*Plus DESCRIBE command. Display the contents of the view
by issuing a SELECT statement.
SELECT *
FROM dept_sum_vu;
Removing a View
You can remove a view without losing data because a view is based on underlying
tables in the database.
Syntax:
DROP VIEW view;
7 rows selected;
Example:
DROP VIEW empvu80;
View dropped.
RESULT:
Thus, the Simple view and Complex view were executed and the outputs were
verified.
Creating a view:
AS
...followed by a normal SQL SELECT. This SELECT can include a WHERE clause or
anything else for that matter that can be put into a SELECT statement. The scenarios
are endless. It really depends on the purpose of the view.
Executing a View
SELECT FIRSTNAME ,
LASTNAME ,
BIRTH_DTTM ,
FULLNAME_FL ,
AGE
FROM VW_STUDENTS1
WHERE AGE IS NOT NULL
/
SQL Sequence
sequence is a feature supported by some database systems to produce unique values on
demand. Some DBMS like MySQL supports AUTO_INCREMENT in place of
Sequence.
AUTO_INCREMENT is applied on columns, it automatically increments the column
value by 1 each time a new record is inserted into the table.
Sequence is also somewhat similar to AUTO_INCREMENT but it has some additional
features too.
Creating a Sequence
Syntax to create a sequence is,
CREATE SEQUENCE sequence-name
START WITH initial-value
25
INCREMENT BY increment-value
MAXVALUE maximum-value
CYCLE | NOCYCLE;
ID NAME
1 abhi
2 adam
4 alex
ID NAME
1 abhi
2 adam
4 alex
1 anu
Once you use nextval the sequence will increment even if you don't Insert any record
into the table.
SQL Synonyms
This Oracle tutorial explains how to create and drop synonyms in Oracle with syntax
and examples.
Description
A synonym is an alternative name for objects such as tables, views, sequences, stored
procedures, and other database objects.
You generally use synonyms when you are granting access to an object from another
schema and you don't want the users to have to worry about knowing which schema
owns the object.
Syntax
The syntax to create a synonym in Oracle is:
OR REPLACE
27
Allows you to recreate the synonym (if it already exists) without having to issue a
DROP synonym command.
PUBLIC
It means that the synonym is a public synonym and is accessible to all users.
Remember though that the user must first have the appropriate privileges to the
object to use the synonym.
schema
The appropriate schema. If this phrase is omitted, Oracle assumes that you are
referring to your own schema.
object_name
The name of the object for which you are creating the synonym. It can be one of
the following:
• table
• view
• sequence
• stored procedure
• function
• package
• materialized view
• java class schema object
• user-defined object
• synonym
Example
Let's look at an example of how to create a synonym in Oracle.
For example:
SELECT *
FROM suppliers;
If this synonym already existed and you wanted to redefine it, you could always use
the OR REPLACE phrase as follows:
28
FOR app.suppliers;
Drop synonym
Once a synonym has been created in Oracle, you might at some point need to drop the
synonym.
Syntax
The syntax to drop a synonym in Oracle is:
PUBLIC
Allows you to drop a public synonym. If you have specified PUBLIC, then you
don't specify a schema.
force
It will force Oracle to drop the synonym even if it has dependencies. It is probably
not a good idea to use force as it can cause invalidation of Oracle objects.
Example
Let's look at an example of how to drop a synonym in Oracle.
For example:
This DROP statement would drop the synonym called suppliers that we defined
earlier.
Ex.No:5
29
Date: HIGH LEVEL PROGRAMMING LANGUAGE EXTENSIONS
(Procedures & Functions)
AIM:
To write a PL/SQL program for executing procedures and functions.
PROCEDURES
ALGORITHM:
Step1: Start the program.
Step2: Declare the variables.
Step3: Create a procedure and select the tuples from the relation stud where
fees=22000 and assign the corresponding course to the variables course.
Step4: Call the procedure up with argument course.
Step5: The value of n is got as input.
Step6: The value is updated ascending to procedure.
Step7: Stop the program.
PROGRAM:
SQL> select * from students;
NAME ID COURSE
--------------- ---------- ---------------
anitha 100 cse
ritu 101 it
Main Program:
SQL> declare
2 a char(3);
3 begin
4 a: ='&a';
5 st(a);
6 end;
7/
30
Sample Output:
Enter value for a: cse
old 4: a:='&a';
new 4: a:='cse';
FUNCTION-I:
AIM:
To write a program to create a function for finding the greatest of three numbers.
ALGORITHM:
Step1: Start the program.
Step2: Create a function named greatest with 3 input arguments a,b,c and output
argument as g.
Step3: If a is greater than b and c, then assign to g else check if b is greater than a
and c, then assign to g else assign c to g.
Step4: Return the value of g.
Step5: Stop the program.
PROGRAM:
SQL> create or replace function greatest(a in number,b in number,c in number) return
number is g number;
2 begin
3 if(a>b)then
4 g:=a;
5 else
6 g:=b;
7 if(c>g)then
8 g:=c;
9 end if;
10 end if;
11 return(g);
12 end;
13 /
Function created.
Main Program:
31
4 d number(3);
5 begin
6 a:=&a;
7 b:=&b;
8 c:=&c;
9 d:=greatest(a,b,c);
10
11 dbms_output.put_line(d);
12 end;
13 /
Sample Output:
Enter value for a: 20
old 6: a:=&a;
new 6: a:=20;
Enter value for b: 50
old 7: b:=&b;
new 7: b:=50;
Enter value for c: 30
old 8: c:=&c;
new 8: c:=30;
OUTPUT:
. SQL> select * from student;
32
NAME ID COURSE FEES
-------------------- ---------- -------------------- ----------
anitha 100 cse 5000
sowmya 101 cse 9000
sashi 123 ece 9000
Sample Output:
Enter value for a: 100
old 5: a:=&a;
new 5: a:=100;
5000
PL/SQL procedure successfully completed.
6. Triggers
33
7. Exception Handling
8. Database Design using ER modeling, normalization and Implementation for any
application
9. Database Connectivity with Front End Tools
10. Case Study using real life database applications
Ex.No:6 Triggers
AIM:
To create the trigger for insertion and deletion operation.
ALGORITHM:
Step1: Start the program.
Step2: Create a trigger with trigger name for insertion operation.
Step3: If insertion command is executed for the corresponding
relations, then raise error.
Step4: Create another trigger with trigger name for delete operation.
Step5: If deletion is executed for the corresponding relation, then raise error.
Step6: Stop the program.
PROGRAM:
SQL> create or replace trigger t1 before insert on student for each row
2 begin
3 if(:new.id>101) then raise_application_error(-20010,'cannot possible');
4 end if;
5 end;
6 /
Trigger created.
1 row created.
SQL> create or replace trigger t2 before delete or update on student for each row
2 begin
3 if updating then raise_application_error(-20013,'no updation');
4 end if;
5 if deleting then raise_application_error(-20014,'no deletion');
6 end if;
7 end;
8/
Trigger created.
34
Sample Output:
SQL> insert into student values('neethu',90);
1 row created.
35
PL/SQL supports programmers to catch such conditions using EXCEPTION block in the
program and an appropriate action is taken against the error condition. There are two types
of exceptions −
• System-defined exceptions
• User-defined exceptions
Syntax for Exception Handling
The general syntax for exception handling is as follows. Here you can list down as many
exceptions as you can handle. The default exception will be handled using WHEN others
THEN −
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
exception1-handling-statements
exception2-handling-statements
exception3-handling-statements
........
exception3-handling-statements
END;
Example
Let us write a code to illustrate the concept. We will be using the CUSTOMERS table we
had created and used in the previous chapters −
DECLARE
36
c_id customers.id%type := 8;
c_name customerS.Name%type;
c_addr customers.address%type;
BEGIN
FROM customers
WHERE id = c_id;
EXCEPTION
dbms_output.put_line('Error!');
END;
When the above code is executed at the SQL prompt, it produces the following result −
No such customer!
Raising Exceptions
Exceptions are raised by the database server automatically whenever there is any internal
database error, but exceptions can be raised explicitly by the programmer by using the
command RAISE. Following is the simple syntax for raising an exception −
DECLARE
exception_name EXCEPTION;
37
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
statement;
END;
You can use the above syntax in raising the Oracle standard exception or any user-defined
exception. In the next section, we will give you an example on raising a user-defined
exception. You can raise the Oracle standard exceptions in a similar way.
User-defined Exceptions
PL/SQL allows you to define your own exceptions according to the need of your program.
A user-defined exception must be declared and then raised explicitly, using either a
RAISE statement or the
procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR.
DECLARE
my-exception EXCEPTION;
Example
The following example illustrates the concept. This program asks for a customer ID, when
the user enters an invalid ID, the exception invalid_id is raised.
DECLARE
c_name customerS.Name%type;
c_addr customers.address%type;
ex_invalid_id EXCEPTION;
BEGIN
38
RAISE ex_invalid_id;
ELSE
FROM customers
WHERE id = c_id;
END IF;
EXCEPTION
dbms_output.put_line('Error!');
END;
When the above code is executed at the SQL prompt, it produces the following result −
Pre-defined Exceptions
PL/SQL provides many pre-defined exceptions, which are executed when any database
rule is violated by a program. For example, the predefined exception
NO_DATA_FOUND is raised when a SELECT INTO statement returns no rows. The
following table lists few of the important pre-defined exceptions −
39
Oracle
Exception SQLCODE Description
Error
40
It is raised when a database call is
NOT_LOGGED_ON 01012 -1012 issued without being connected to
the database.
To Use VB as front end and study about the VB front end tools.
Introduction:
VISUAL BASIC is a high level programming language which was evolved from
the earlier DOS version called BASIC. BASIC means Beginners' All-purpose
Symbolic Instruction Code. It is a very easy programming language to learn. The
codes look a lot like English Language. Different software companies produced
different version of BASIC, such as Microsoft QBASIC, QUICKBASIC, GWBASIC
,IBM BASICA and so on. However, it seems people only use Microsoft Visual Basic
today, as it is a well developed programming language and supporting resources are
available everywhere. Now, there are many versions of VB exist in the market, the
most popular one and still widely used by many VB programmers is none other than
Visual Basic 6. We also have VB.net, VB2005 and the latest VB2008, which is a fully
object oriented programming (OOP) language.
On the other hand, because users may click on certain object randomly, so each
object has to be programmed independently to be able to response to those actions
(events). Therefore, a VB Program is made up of many subprograms, each has its own
program codes, and each can be executed independently and at the same time each can
be linked together in one way or another.
42
What programs can you create with Visual Basic 6?
With VB 6, you can create any program depending on your objective. For
example, if you are a college or university lecturer, you can create educational
programs to teach business, economics, engineering, computer science, accountancy ,
financial management, information system and more to make teaching more effective
and interesting. If you are in business, you can also create business programs such as
inventory management system , point-of-sale system, payroll system, financial
program as well as accounting program to help manage your business and increase
productivity. For those of you who like games and working as games programmer,
you can create those programs as well. Indeed, there is no limit to what program you
can create ! There are many such programs in this tutorial, so you must spend more
time on the tutorial in order to learn how to create those programs.
INTRODUCTION TO FORMS:
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 labelling the development environment.
43
The above diagram shows the development environment with all the important
points labelled. 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
44
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.
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.
45
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.
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.
Once an application is loaded it can be run by click on the icon from the toolbar, to
pause press and to terminate use .
46
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
Save your work to disk. Use the Windows Explorer or any desktop windows to
check that all files have been saved. There should be one Visual Basic Project (.VBP) file
and separate Form (.FRM) and Module (.BAS) files for each form and module used in
the current project.
47
Property Description
Name The name of the object so you can call it at runtime
This specifies the command button's background color. Click the
BackColor's palette down arrow to see a list of common Windows
BackColor
control colours, you must change this to the style property from 0 -
standard to 1 - graphical
Determines whether the command button gets a Click event if the user
Cancel
presses escape
Caption Holds the text that appears on the command button.
Determins if the command button responds to an enter keypress even if
Default
another control has the focus
Determines whether the command button is active. Often, you'll change
Enable the enable property at runtime with code to prevent the user pressing the
button
Produces a Font dialog box in which you can set the caption's font name ,
Font
style and size.
Height Positions the height of the object - can be used for down
Left Positions the left control - can be used for right
If selected to an icon can change the picture of the mouse pointer over
MousePointer
that object
Hold's the name of an icon graphic image so that it appears as a picture
Picture instead of a Button for this option to work the graphical tag must be set
to 1
This determins if the Command Button appears as a standard windows
Style
dialog box or a graphical image
Tab index Specifies the order of the command button in tab order
Whether the object can be tabbed to ( this can be used in labels which
Tab Stop
have no other function )
If the mouse is held over the object a brief description can be displayed
Tool Tip Text (for example hold your mouse over one of the above pictures to see this
happening
If you want the user to see the button/label select true other wise just
Visible
press false
Width Show the width of the object
EVENTS
The ‘look’ of a Visual Basic application is determined by what controls are used,
but the ‘feel’ is determined by the events. An event is something which can happen to a
control. For example, a user can click on a button, change a text box, or resize a form. As
explained in Creating a Visual Basic Application, writing a program is made up of three
events: 1) select suitable controls, 2) set the properties, and 3) write the code. It is at the
code writing stage when it becomes important to choose appropriate events for each
control. To do this double click on the control the event will be used for, or click on the
48
icon in the project window (usually top right of screen). A code window should now
be displayed similar to the one shown below.
The left hand dropdown box provides a list of all controls used by the current form,
the form itself, and a special section called General Declarations. The corresponding
dropdown box on the right displays a list of all events applicable to the current control
(as specified by the left hand dropdown box). Events displayed in bold signify that
code has already been written for them, unbold events are unused. To demonstrate that
different events can play a significant role in determining the feel of an application, a
small example program will be written to add two numbers together and display the
answer. The first solution to this problem will use the click event of a command
button, while the second will the change event of two text boxes.
Click Event
Before any events can be coded it is necessary to design the interface from suitable
controls. As shown in the screen shot below use: 2 text boxes to enter the numbers, a
label for the ‘+’ sign, a command button for the ‘=’ sign, and another label for the
answer.
Making the click event is very simple just select the button with the mouse and double
click visual basic will generate
In the first example the user has to enter two numbers and then click on the equals button
to produce an answer. However, the program can be changed so that the answer will be
calculated every time either of the two numbers are changed without requiring an equals
button.
49
To do this first remove the equals command button and replace it with a label with the
caption set to ‘=’. Now, bring up a code window and copy to the Windows clipboard
the line lblAnswer = Str$(Val(txtNumber1.Text) + Val(txtNumber2.Text)). Using
the left hand dropdown box select the first text box and then select the Change event
from the right dropdown box. Then paste the code from the clipboard into the empty
subroutine. Select the second text box and do the same. The same line is required
twice because the two click events belong to two separate controls. The final code
should look like:
Run the program again, enter the two numbers and observe what happens. Each time a
digit changes the answer is recalculated.
Note: There may be times when recalculating more advanced problems takes too long
on each change and so requiring the user to enter all the data first and then click on an
answer button might more appropriate.
So far only one event has been used per control, however this does not have to be the
case! Add a StatusBar control to the bottom of the form, bring up the code window
using , select the first text box (txtNumber1) from the left hand dropdown box, and
then select the GotFocus event from the right hand dropdown box. Now some basic
instructions can be written in the status bar so that when the cursor is in the text box
(the text box has focus) the status bar reads “Enter the first number”. After completing
this change to the second text box and using the same GotFocus event change the
statusbar text to “Enter a second number”. The code to set the status bar can be seen
below.
CheckBoxes
Option bars are used quite often in the windows environment as they can only have two
outputs 0 and 1 these get used to process the form. In this example it will be used to
change the some text from normal to bold or to italic.
50
Private Sub chkBold_Click()
If chkBold.Value = 1 Then ' If checked.
txtDisplay.FontBold = True
Else ' If not checked.
txtDisplay.FontBold = False
End If
End Sub
Note: If you create the frame first and then add the option buttons by single clicking
on the toolbox and dragging the cross hair cursor on the frame to create the controls,
they will be attached to the frame and will move with it if you decide to re-position the
frame. Notice, however, that if you create the frame first and double click the screen
controls, then drag them from the centre of the form on to the frame, they will not be
attached to it and will be left behind when you try to move the frame. Try this out.
Notice that when you run your application the same icon is loaded first (probably the
clipboard, if you created that option button first). You can alter the option that has the
focus first, by selecting one of the other option buttons and setting its property
tabindex to 1.
Option Buttons
List boxes
Note :
List boxes and combo boxes are used to supply a list of options to the user. The
toolbox icons representing these two controls are for list box and for combo
box.
A list box is used when the user is to be presented with a fixed set of selections
(i.e. a choice must be made only from the items displayed, there is no possibility of the
user typing in an alternative).
To create a list box, double click on the toolbox icon . Drag the resulting box
into place on the form and size it according to the data it will hold. The left hand
picture below shows a list box that has been created and sized on Form1. In the middle
is the code that is required to load a selection of cars into the list. The data has been
included in the procedure Sub Form_Load so that it appears when Form1 is loaded.
Finally, the picture on the right shows what appears on the form when the application
is run. Notice that vertical scroll bars are added automatically if the list box is not deep
enough to display all the choices.
52
If you however add the following source code to this project
Add to a Lisbox
53
Note: They appear in the order they were typed if you changed the properties window by
changing sort order = true then they will go into alpaetical order. List items can be added
and deleted all the list is counted as the order they are in so for exapmple if you wanted to
delete "Tuesday" you would type
list1.RemoveItem 1
Note: The property ListCount stores the number of items in a list, so list1.ListCount
can be used to determine the number of items in list box list1.
The property ListIndex gives the index of the currently selected list item. So the
statement list1.RemoveItem List1.ListIndex removes the currently highlighted list
item.
Adding an item can be accomplished very neatly using an input dialog box. Try this:
This will open a message box and prompt you for a new day to enter this will then be
added to the list index at the bottem unless you specify were it should go.
Combo Boxes
Combo boxes are of three types (0,1 and 2), setting their properties/styles determines the
type. Combo boxes (style 0 and 2 ) are a good choice if space is limited, becaue the full
list is displayed as a drop down list, it does not occupy screen space until the down arrow
is clicked.
The user can either enter text in the edit field or select from the list of items by
clicking on the (detached) down arrow to the right. The drop-down Combo box, list is
viewed by clicking on the down arrow. This type of combo box does not have a down
arrow because the list is displayed at all times. If there are more items than can be
shown in the size of box you have drawn, vertical scroll bars are automatically added.
As with previous type, users can enter text in the edit field.
54
It is slightly confusing to find this control under combo box. This control behaves like
a regular list box except that the choices are not revealed until the down arrow is
clicked. The user can select only from the choices given, there is no text entry facility.
Note: Combo boxes of style 0 and 2 cannot respond to double click events.
Msgboxes
Message boxes are used when you want to ask the user a question or display an error
message(s) and advise the user. There are six types of message boxes here are their
functions and what they do. Here is the listing of all the possible msgbox events
The Buttons displayed in a message
here Value Short Description
Button Layout
vbOKonly 0 Displays the OK button.
vbOKCancel 1 Displays the ok and cancel button.
vbAbortRetryIgnore 2 Displays the Abort , Retry , Ignore
vbYesNoCancel 3 Displays Yes , No and Cancel button
vbYesNo 4 Displays the Yes / No button
Displays the retry and Cancel
vbRetryCancel 5
buttons.
The Default button displayed in a message form Default Value Short Description
Button
Button 1 is
vbDefaultButton1 0
default
Button 2 is
vbDefaultButton2 256
default
Button 3 is
vbDefaultButton3 512
default
55
Msgbox Return Value Return Value Value Short Description
vbOk 1 The User Clicked OK
vbCancel 2 The User Clicked Cancel
vbAbort 3 The User Clicked Abort
vbRetry 4 The User Clicked Retry
vbIgnore 5 The User Clicked Ignore
VbYes 6 The User Clicked Yes
VbNo 7 The User Clicked No
The syntax for use of the message box in Mgsgbox "TEXT", VALUE, "TITLE"
If you want to use two or more tables just add the values together. Therefore to print a
message box to say "The Device was not Found!" OK & Explanation :
Source code 1
End Sub
Source code 2
End Sub
You should get the picture shown below whatever source code you used.
This is a basic msgbox which in this case has not been processed in any way. The
following Source code displays a msgbox that ask you for specific text. For example
lets make a password program out of this message box.
lngBefore = Timer
Do
strAns = InputBox("What is the password Password is Example", "Password
56
Required")
Loop Until Val(strAns) = Example
lngAfter = Timer
msgbox "Correct Password", vbInformation
End Sub
Once you copy and paste the source code you should get prompted for a password in a
different type of msgbox as it includes text. From looking at this example you should
be able to see how the loop function works to generate and then check the value. All
of the Return Values work in the same way to return an object input.
Visual Basic is it's easy way of accessing and modifying databases.There are
many ways to work with databases in Visual Basic, with data control.
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:
You should really specify the complete path to the db, but if your current directory is the
directory where the database is situated, this will work.
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.
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
57
VB's online help file explains the different modes and what they ar e 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
End Sub
This will make the list box fill up with your records when the form loads. I have
introduced some new concepts with this example. We have all ready covered the first part
where we open the table. 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.
Put a text box somewhere on the form and call it "txtPhone". Then copy the
following code to the project.
Private Sub lstRecords_Click()
End Sub
58
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.
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.
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
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. T he 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()
rsMyRS.Delete
lstRecords.RemoveItem lstRecords.ListIndex
End Sub
Adding
Adding records is much like updateing, 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"
59
lstRecords.AddItem rsMyRS!Name
lstRecords.ItemData(lstRecords.NewIndex) = rsMyRS!ID
rsMyRS!Phone = "Person's Phone Number"
rsMyRS.Update
End Sub
Library System
The Library system was created using ADO. ADO stands for ActiveX data
objects. As ADO is ActiveX-based, it could work in different platforms (different
computer systems) and different programming languages. Besides, it could access many
different kinds of data such as data displayed in the Internet browsers, email text and
even graphics other than the usual relational and non relational database information.
To be able to use ADO data control, you need to insert it into the toolbox. To do this,
simply press Ctrl+T to open the components dialog box and select Microsoft ActiveX
Data Control 6. After this, you can proceed to build your ADO-based VB database
applications.
The following example will illustrate how to build a relatively powerful database
application using ADO data control. First of all, name the new form as frmBookTitle and
change its caption to Book Tiles- ADO Application. Secondly, insert the ADO data
control and name it as adoBooks and change its caption to book. Next, insert the
necessary labels, text boxes and command buttons. The runtime interface of this program
is shown in the diagram below, it allows adding and deletion as well as updating and
browsing of data.
60
The properties of all the controls are listed as follow:
Form Name frmBookTitle
Book Titles -
Form Caption
ADOApplication
ADO Name adoBooks
Label1 Name lblApp
Label1 Caption Book Titles
Label 2 Name lblTitle
Label2 Caption Title :
Label3 Name lblYear
Label3 Caption Year Published:
Label4 Name lblISBN
Label4 Caption ISBN:
Labe5 Name lblPubID
Label5 Caption Publisher's ID:
Label6 Name lblSubject
Label6 Caption Subject :
TextBox1 Name txtitle
TextBox1 DataField Title
TextBox1 DataSource adoBooks
TextBox2 Name txtPub
TextBox2 DataField Year Published
TextBox2 DataSource adoBooks
TextBox3 Name txtISBN
TextBox3 DataField ISBN
TextBox3 DataSource adoBooks
TextBox4 Name txtPubID
TextBox4 DataField PubID
TextBox4 DataSource adoBooks
TextBox5 Name txtSubject
TextBox5 DataField Subject
61
TextBox5 DataSource adoBooks
Command Button1
cmdSave
Name
Command Button1
&Save
Caption
Command Button2
cmdAdd
Name
Command Button2
&Add
Caption
Command Button3
cmdDelete
Name
Command Button3
&Delete
Caption
Command Button4
cmdCancel
Name
Command Button4
&Cancel
Caption
Command Button5
cmdPrev
Name
Command Button5
&<
Caption
Command Button6
cmdNext
Name
Command Button6
&>
Caption
Command Button7
cmdExit
Name
Command Button7
E&xit
Caption
To be able to access and manage a database, you need to connect the ADO data control to
a database file. We are going to use BIBLIO.MDB that comes with VB6. To connect
ADO to this database file , follow the steps below:
a) Click on the ADO control on the form and open up the properties window.
b) Click on the ConnectionString property, the following dialog box will appear.
62
when the dialog box appear, select the Use Connection String's Option. Next, click build
and at the Data Link dialog box, double-Click the option labeled Microsoft Jet 3.51 OLE
DB provider.
After that, click the Next button to select the file BIBLO.MDB. You can click on Text
Connection to ensure proper connection of the database file. Click OK to finish the
connection.
Finally, click on the RecordSource property and set the command type to adCmd Table
and Table name to Titles. Now you are really to use the database file.
63
Now, you need to write code for all the command buttons. After which, you can make the
ADO control invisible.
For the Save button, the program codes are as follow:
Sample code
End Sub
For the Add button, the program codes are as follow:
Private Sub cmdAdd_Click()
adoBooks.Recordset.AddNew
End Sub
For the Delete button, the program codes are as follow:
Private Sub cmdDelete_Click()
Confirm = MsgBox("Are you sure you want to delete this record?", vbYesNo, "Deletion
Confirmation")
If Confirm = vbYes Then
adoBooks.Recordset.Delete
MsgBox "Record Deleted!", , "Message"
Else
MsgBox "Record Not Deleted!", , "Message"
64
End If
End Sub
65
66