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

Ex.

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:

SQL> create table student (name varchar2 (20),rollno number(5));

Table created.

SQL> desc student;


Name Null? Type
----------------------------------------- -------- ----------------------------
NAME VARCHAR2 (20)
ROLLNO NUMBER (5)

1
ALTER (ADD) COMMAND:

SQL> alter table student add (fees number (6));

Table altered.

SQL> desc student;


Name Null? Type
----------------------------------------- -------- ----------------------------
NAME VARCHAR2 (20)
ROLLNO NUMBER (5)
FEES NUMBER (6)

ALTER (MODIFY) COMMAND


SQL> alter table student modify (rollno number (10));

Table altered.

SQL> desc student;


Name Null? Type
----------------------------------------- -------- ----------------------------
NAME VARCHAR2 (20)
ROLLNO NUMBER (10)
FEES NUMBER (6)

TRUNCATE COMMAND:

SQL> truncate table student;

Table truncated.

DROP COMMAND:

SQL> drop table student;

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:

To study and execute DML and DCL commands in RDBMS

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:

SQL> create table dml(sname varchar2(15),rno number(5),course varchar(9),fees


number(12));

Table created.

SQL> desc dml;


Name Null? Type
----------------------------------------- -------- ----------------------------
SNAME VARCHAR2(15)
RNO NUMBER(5)
COURSE VARCHAR2(9)
FEES NUMBER(12)

INSERT COMMAND:

SQL> insert into dml values('&sname',&rno,'&course',&fees);


Enter value for sname: anju
Enter value for rno: 101
Enter value for course: cse
Enter value for fees: 40000
old 1: insert into dml values('&sname',&rno,'&course',&fees)
new 1: insert into dml values('anju',101,'cse',40000)

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:

SQL> alter table dml add(address varchar(17));

Table altered.

SQL> select * from dml;

SNAME RNO COURSE FEES ADDRESS


--------------- ---------- --------- ---------- -----------------
anju 101 cse 40000
keerthi 106 it 50000
ramu 107 cse 40000
rini 108 eee 50000

UPDATE COMMAND:

SQL> update dml set fees=60000 where course='cse';

2 rows updated.

SQL> select *from dml;

SNAME RNO COURSE FEES ADDRESS


--------------- ---------- --------- ---------- -----------------
anju 101 cse 60000
keerthi 106 it 50000
ramu 107 cse 60000
rini 108 eee 50000

DELETE COMMAND:

SQL> delete from dml where sname='rini';

5
1 row deleted.

SQL> select *from dml;

SNAME RNO COURSE FEES ADDRESS


--------------- ---------- --------- ---------- -----------------
anju 101 cse 60000
keerthi 106 it 50000
ramu 107 cse 60000

DATA CONTROL LANGUAGE (DCL):


Data control language, the previous user with privileges commands the database
object(table, view, etc) of a user cant be accessed by another user without the permission
of a user. The owner can allow other user to access his object as per his diversion the
permission given by a user to another is called privilege.
The Data Control Commands are:
i. GRANT Privilege
ii. REVOKE Privilege

COMMIT COMMAND:

SQL> commit;
Commit complete.
ROLLBACK COMMAND:

SQL> rollback;

Rollback complete.

SQL> select *from dml;

SNAME RNO COURSE FEES ADDRESS


--------------- ---------- --------- ---------- -----------------
anju 101 cse 60000
keerthi 106 it 50000
ramu 107 cse 60000

SQL> delete from dml where rno=101;

1 row deleted.

SQL> select * from dml;

6
SNAME RNO COURSE FEES ADDRESS
--------------- ---------- --------- ---------- -------------
keerthi 106 it 50000
ramu 107 cse 60000

SQL> rollback;

Rollback complete.

SQL> select * from dml;

SNAME RNO COURSE FEES ADDRESS


--------------- ---------- --------- ---------- -------------
anju 101 cse 60000
keerthi 106 it 50000
ramu 107 cse 60000

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

SQL> grant select,insert,update,delete on dml to public;

Grant succeeded.

TO CHECK:

SQL> delete from dml where rno=107;

1 row deleted.

SQL> select *from dml;

SNAME RNO COURSE FEES ADDRESS


--------------- ---------- --------- ---------- -----------------
anju 101 cse 60000
keerthi 106 it 50000
Object Privilege:

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;

SQL> revoke select,insert,update,delete on dml from public;

Revoke succeeded.

RESULT:
Thus the basic DML, DCL and TCL commands are successfully executed and the output
is verified.

EXPT NO: 1C TRANSACTION CONTROL LANGUAGE


All changes made to the database is defined as a transaction. It is logical unit of work.
The transaction can made permanent to a database only they are committed. A transaction
begins
with an executable SQL statement. The two transaction control commands are:
1. COMMIT:
1. COMMIT
2. ROLLBACK
This command is used to make all transaction changes permanent to the database.
This command erases all save point and release the transaction lock.
Syntax:
COMMIT
SAVEPOINT:
It is not a command. It is only a marker. Save point are used to divide as lengthy
transaction into smaller ones.
Syntax:

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.

Ex.No:2 DATABASE QUERYING – SIMPLE QUERIES, NESTED QUERIES,


SUB QUERIES & JOIN QUERIES
AIM:
To perform the simple queries, nested queries, sub queries & join queries in SQL.

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;

Name Null? Type


------------ -------------------- ---------------
ENO NOT NULL NUMBER(3)
ENAME VARCHAR2(25)
ADDRESS VARCHAR2(30)
BASIC_SALARY NUMBER(12,2)
JOB_STATUS VARCHAR2(15)
DNO NUMBER(3)

SQL>desc pro_det;

Name Null? Type


------------ -------------------- ---------------
PNO NOT NULL NUMBER(3)
PNAME VARCHAR2(30)
NOS_OF_STAFF NUMBER(3)

SQL>desc work_in;

Name Null? Type


------------ -------------------- ---------------
PNO NUMBER(3)
ENO NUMBER(3)
PJOB CHAR(12)

SQL>select * from emp_det;

Sample Output:

ENO ENAME ADDRESS BASIC_SALARY JOB_STATUS DNO


-------- -------------- --------------- ----------------- ------------- ---------- -----------
1 abi erode 8000 manager 10
2 deepak erode 8500 manager 10
3 anjali raj street 10000 assistant 2
4 geetha abc nagar 7800 professor 3
5 shirley kk nagar 7888 assistant 3
6 kiruthi kovai 10000 professor 2
7 chindu mmnagar 7800 professor 2

7 rows selected

SQL>select * from pro_det;


14
Output:

PNO PNAME NOS_OF_STAFF


------------- ---------------- ------------------------------
1 DBMS 3
2 COMPILER 2
3 C 3

3 rows selected

SQL>select * from work_in;

Output:

PNO ENO PJOB


1 1 programmer
2 1 analyst
1 2 analyst
2 2 programmer

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;

NAME NULL? TYPE


----- - --------- -------------- --------- ------- ----------
Order_id number(6)
Supplier_id number(5)
Order_date date

SQL>select * from suppliers;

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:

SQL>select * from supplier,ord where supplier.supid=ord.supid;

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:

Left outer join:

SQL>select supplier.suPID ,supplier.suPNAME,ord.oDATE where


supplier.suPID(+)=ord.suPID;

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

Right outer join:

SQL>select supplier.suPID ,supplier.suPNAME,ord.oID,ord.oDATE from supplier.ord


where supplier.suPID = ord.suPID(+);

Output:

SuPID SuPNAME oid Odate


-------- --------- --------- --------- -------- -------------
12 abi 111 1/9/09
14 nithi 333 6/9/09
15 selvi 555 17/9/09
13 chindu

16
Full outer join:

SQL>select * from supplier,ord where supplier.suPID(+) = ord.suPID(+)


Union select * from supplier,ord where supplier.suPID=ord.suPID(+);

Sample Output:

SuPID SuPNAME oid supid Odate


--------- --------- --------- --------- -------- ------------- ----
12 abi 111 12 1/9/09
13 chindu
14 nithi 333 14 6/9/09
15 selvi 555 15 17/9/09
222 23 8/9/09
444 25 3/9/09
Example Queries:

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

05. Find name,job_status,basic_salary of the employees who are worked in chindu’s


department and also get the same salary.

SQL>select ename, job_status,basic_salary from emp_det


where(dno,basic_salary)in(select dno,basic_salary from emp_det where
ename=’chindu’);

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

07. List the employees who draw highest salary.

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

08. List the second maximum salary.

SQL>select max(basic_salary)from emp_det where basic_salary < (select


max(basic_salary)from emp_det);

Output:
MAX(BASIC_SALARY)
----------- ----------------------
8500

09. List the salary where basic is less than the average salary.

SQL>select * from emp_det where basic_salary <(select avg(basic_salary)from


emp_det);

Output:

ENO ENAME ADDRESS BASIC_SALARY JOB_STATUS DNO


-------- -------------- --------------- ----------------- ------------- ---------- -----------
1 abi erode 8000 manager 10
2 deepak erode 8500 manager 10
4 geetha abc nagar 7800 professor 3
5 shirley kk nagar 7888 assistant 3
7 chindu mmnagar 7800 professor 2

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.

Many different perspectives of the same table.

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:

CREATE OR REPLACE VIEW vw_STUDENTS1


AS
SELECT
FIRSTNAME,
LASTNAME,
BIRTH_DTTM,
(FIRSTNAME || ' ' || LASTNAME) "FULLNAME_FL",
24
trunc(months_between(sysdate,BIRTH_DTTM)/12)
"AGE"
FROM COURSEREGISTRATION.STUDENTS
/

The syntax for creating a view is...

CREATE OR REPLACE VIEW `<your_view_name>`

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

Execute an SQL 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;

• The initial-value specifies the starting value for the Sequence.


• The increment-value is the value by which sequence will be incremented.
• The maximum-value specifies the upper limit or the maximum value upto which
sequence will increment itself.
• The keyword CYCLE specifies that if the maximum value exceeds the set limit,
sequence will restart its cycle from the begining.
• And, NO CYCLE specifies that if sequence exceeds MAXVALUE value, an error
will be thrown.

Using Sequence in SQL Query


Let's start by creating a sequence, which will start from 1, increment by 1 with a
maximum value of 999.
CREATE SEQUENCE seq_1
START WITH 1
INCREMENT BY 1
MAXVALUE 999
CYCLE;

Now let's use the sequence that we just created above.


Below we have a class table,

ID NAME

1 abhi

2 adam

4 alex

The SQL query will be,


26
INSERT INTO class VALUE(seq_1.nextval, 'anu');
Resultset table will look like,

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.

Create Synonym (or Replace)


You may wish to create a synonym so that users do not have to prefix the table name
with the schema name when using the table in a query.

Syntax
The syntax to create a synonym in Oracle is:

CREATE [OR REPLACE] [PUBLIC] SYNONYM [schema .] synonym_name


FOR [schema .] object_name [@ dblink];

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:

CREATE PUBLIC SYNONYM suppliers


FOR app.suppliers;

This first CREATE SYNONYM example demonstrates how to create a synonym


called suppliers. Now, users of other schemas can reference the table
called suppliers without having to prefix the table name with the schema named app.
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:

CREATE OR REPLACE PUBLIC SYNONYM suppliers

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:

DROP [PUBLIC] SYNONYM [schema .] synonym_name [force];

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:

DROP PUBLIC SYNONYM suppliers;

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

SQL> create or replace procedure st(course in char) is


2 begin
3 update students set id=101 where course='cse';
4 end;
5 /
Procedure created.

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';

PL/SQL procedure successfully completed.

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:

SQL> declare a number(3);


2 b number(3);
3 c number(3);

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;

PL/SQL procedure successfully completed.

SQL> select greatest (20, 50, 30) from dual;

GREATEST (20, 50, 30)


------------------
50
FUNCTIONS-II
AIM:
To write an PL/SQL program to print the fees of students whose roll no is given as
input using functions.
ALGORITHM:
Step1: Start the program.
Step2: Create a function named fun to print the fees of student whose roll no is
given.
Step3: Get the value of roll no.
Step4: Call the function and return the value of fees.
Step5: Stop the program.

OUTPUT:
. SQL> select * from student;
32
NAME ID COURSE FEES
-------------------- ---------- -------------------- ----------
anitha 100 cse 5000
sowmya 101 cse 9000
sashi 123 ece 9000

SQL> create or replace function fn(roll in number)return number is n number;


2 begin
3 select fees into n from student where id=roll;
4 return (n);
5 end;
6/
Function created.
Main Program:
SQL> set serveroutput on
SQL> declare
2 a number (5);
3 b number (6);
4 begin
5 a:=&a;
6 b: =fn (a);
7 dbms_output.put_line(b);
8 end;
9/

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.

SQL> insert into student values ('spandu', 99);

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.

SQL> insert into student values('neethu',111);


insert into student values('neethu',111)
*
ERROR at line 1:
ORA-20010: cannot possible
ORA-06512: at "SCOTT.T1", line 2
ORA-04088: error during execution of trigger 'SCOTT.T1'

SQL> delete from student where id=102;


delete from student where id=102
*
ERROR at line 1:
ORA-20014: no deletion
ORA-06512: at "SCOTT.T2", line 4
ORA-04088: error during execution of trigger 'SCOTT.T2'

SQL> update student set id=123 where id=102;


update student set id=123 where id=102
*
ERROR at line 1:
ORA-20013: no updation
ORA-06512: at "SCOTT.T2", line 2
ORA-04088: error during execution of trigger 'SCOTT.T2'

EXPT NO: 7 Exception Handling

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

<exception handling goes here >

WHEN exception1 THEN

exception1-handling-statements

WHEN exception2 THEN

exception2-handling-statements

WHEN exception3 THEN

exception3-handling-statements

........

WHEN others THEN

exception3-handling-statements

END;

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

SELECT name, address INTO c_name, c_addr

FROM customers

WHERE id = c_id;

DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);

DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);

EXCEPTION

WHEN no_data_found THEN

dbms_output.put_line('No such customer!');

WHEN others THEN

dbms_output.put_line('Error!');

END;

When the above code is executed at the SQL prompt, it produces the following result −

No such customer!

PL/SQL procedure successfully completed.


The above program displays the name and address of a customer whose ID is given. Since
there is no customer with ID value 8 in our database, the program raises the run-time
exception NO_DATA_FOUND, which is captured in the EXCEPTION block.

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

WHEN exception_name THEN

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.

The syntax for declaring an exception is −

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_id customers.id%type := &cc_id;

c_name customerS.Name%type;

c_addr customers.address%type;

-- user defined exception

ex_invalid_id EXCEPTION;

BEGIN

IF c_id <= 0 THEN

38
RAISE ex_invalid_id;

ELSE

SELECT name, address INTO c_name, c_addr

FROM customers

WHERE id = c_id;

DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);

DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);

END IF;

EXCEPTION

WHEN ex_invalid_id THEN

dbms_output.put_line('ID must be greater than zero!');

WHEN no_data_found THEN

dbms_output.put_line('No such customer!');

WHEN others THEN

dbms_output.put_line('Error!');

END;

When the above code is executed at the SQL prompt, it produces the following result −

Enter value for cc_id: -6 (let's enter a value -6)


old 2: c_id customers.id%type := &cc_id;
new 2: c_id customers.id%type := -6;
ID must be greater than zero!

PL/SQL procedure successfully completed.

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

It is raised when a null object is


ACCESS_INTO_NULL 06530 -6530
automatically assigned a value.

It is raised when none of the choices


in the WHEN clause of a CASE
CASE_NOT_FOUND 06592 -6592
statement is selected, and there is no
ELSE clause.

It is raised when a program attempts


to apply collection methods other
than EXISTS to an uninitialized
COLLECTION_IS_NULL 06531 -6531 nested table or varray, or the
program attempts to assign values to
the elements of an uninitialized
nested table or varray.

It is raised when duplicate values are


DUP_VAL_ON_INDEX 00001 -1 attempted to be stored in a column
with unique index.

It is raised when attempts are made


to make a cursor operation that is
INVALID_CURSOR 01001 -1001
not allowed, such as closing an
unopened cursor.

It is raised when the conversion of a


character string into a number fails
INVALID_NUMBER 01722 -1722
because the string does not represent
a valid number.

It is raised when a program attempts


LOGIN_DENIED 01017 -1017 to log on to the database with an
invalid username or password.

It is raised when a SELECT INTO


NO_DATA_FOUND 01403 +100
statement returns no rows.

40
It is raised when a database call is
NOT_LOGGED_ON 01012 -1012 issued without being connected to
the database.

It is raised when PL/SQL has an


PROGRAM_ERROR 06501 -6501
internal problem.

It is raised when a cursor fetches


ROWTYPE_MISMATCH 06504 -6504 value in a variable having
incompatible data type.

It is raised when a member method


SELF_IS_NULL 30625 -30625 is invoked, but the instance of the
object type was not initialized.

It is raised when PL/SQL ran out of


STORAGE_ERROR 06500 -6500
memory or memory was corrupted.

It is raised when a SELECT INTO


TOO_MANY_ROWS 01422 -1422 statement returns more than one
row.

It is raised when an arithmetic,


VALUE_ERROR 06502 -6502 conversion, truncation, or
sizeconstraint error occurs.

It is raised when an attempt is made


ZERO_DIVIDE 01476 1476
to divide a number by zero.

EXPTNO: 9 Database Connectivity with Front End Tools

FRONT END TOOLS


41
Aim:

To Use VB as front end and study about the VB front end tools.

Introduction:

What is Visual Basic?

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.

VISUAL BASIC is a VISUAL and events driven Programming Language. These


are the main divergence from the old BASIC. In BASIC, programming is done in a
text-only environment and the program is executed sequentially. In VB, programming
is done in a graphical environment. In the old BASIC, you have to write program
codes for each graphical object you wish to display it on screen, including its position
and its color. However, In VB , you just need to drag and drop any graphical object
anywhere on the form, and you can change its color any time using the properties
windows.

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.

FORMS & MENU DESIGN

INTRODUCTION TO FORMS:

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

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.

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 :

• The Blank Form window


• The Project window
• 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.

Understanding the tool box.

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.

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 .

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.

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

Saving your visual basic project.

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.

Button Properties for reference

, Command Button & labels properties

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

You can see on the top right there is a 'click'


dropdown list this is known as a event handler.

Writing your own even

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:

Private Sub txtNumber1_Change()


label2.Caption = Str$(Val(text1.Text) + Val(text.Text))
End Sub

Private Sub txtNumber2_Change()


label2.Caption = Str$(Val(text1.Text) + Val(text2.Text))
End Sub

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.

Using the event GotFocus event

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

Private Sub chkItalic_Click()


If chkItalic.Value = 1 Then ' If checked.
txtDisplay.FontItalic = True
Else ' If not checked.
txtDisplay.FontItalic = False
End If
End Sub

This example can be found at "smaples/PGuide/controls/Controls.vbp" or


downloaded free from the download page.
The checkboxes can be turned on at runtime by simply typing

name.value = 1 ' 1 On , 0 off

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

Changing the background colour


51
Changing the background colour gets used mostly by freeware, or the type of programs
you generate for use with banners or adverts, anyway it might come in useful sometime.
This example shows an ordinary picture of a smiley face then I put in some nice
background colours to make it stand out more.

Private Sub Form_Load()


BackColor = QBColor(Rnd * 15)
ForeColor = QBColor(Rnd * 10)
Picture1.BackColor = QBColor(Rnd * 15)
Picture1.ForeColor = QBColor(Rnd * 10)
End Sub

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

Private Sub Form_Load()


List1.AddItem "Monday"
List1.AddItem "Tuesday"
List1.AddItem "Wedsday"
List1.AddItem "Thursday"
List1.AddItem "Friday"
List1.AddItem "Saturday"
List1.AddItem "Sunday"
End Sub

The source code should look somthing like this :

Removing & Advanced Options

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

And to add to the list in a paticular order just add

list1.additem "My Day", 5

This will be added after saturday.

And finally to clear the lisbox type

List1.clear This will completly clear the contence of the listbox.

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:

list1.AddItem InputBox("Enter a day", "Add a Day")

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.

Picture of combo box style 0

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.

Drop-down List box (Style=2)

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 Icons dispayed in the message box are here

Icon on message Value Short Description


vbCritical 16 Displays critical message icon
vbQuestion 32 Displays question icon
vbExclamation 48 Displays exclamation icon
vbInformation 64 Displays information icon

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

Private Sub Form_Load()

MsgBox "The Device was not Found!", 48, "Header"

End Sub

Source code 2

Private Sub Form_Load()

MsgBox "The Device was not found!", vbExclamation, "Header"

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.

Private Sub Form_Load()

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.

DATA BASE DESIGN AND IMPLEMENTATION


Data base design:

Introduction to the usages of Access data bases

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.

DAO (Data Access Objects). Opening a database and retrieving/adding/


deleting/updating records from tables. Access Database (*.mdb) ,this is the most used
DBMS (DataBase Management System) for smaller applications made in Visual Basic.

Eg: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:

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")

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

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

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

Private Sub Form_Load()

Set dbMyDB = OpenDatabase("MyDatabase.mdb")


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

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. 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()

rsMyRS.FindFirst "ID=" & Str(lstRecords.ItemData(lstRecords.ListIndex))


txtPhone.Text = rsMyRS!Phone

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.

Updating the Database

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.

Private Sub cmdNew_Click()

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

EXPT: 10. Case Study using real life database applications

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

Private Sub cmdSave_Click()


adoBooks.Recordset.Fields("Title") = txtTitle.Text
adoBooks.Recordset.Fields("Year Published") = txtPub.Text
adoBooks.Recordset.Fields("ISBN") = txtISBN.Text
adoBooks.Recordset.Fields("PubID") = txtPubID.Text
adoBooks.Recordset.Fields("Subject") = txtSubject.Text
adoBooks.Recordset.Update

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

For the Cancel button, the program codes are as follow:


Private Sub cmdCancel_Click()
txtTitle.Text = ""
txtPub.Text = ""
txtPubID.Text = ""
txtISBN.Text = ""
txtSubject.Text = ""
End Sub

For the Previous (<) button, the program codes are

Private Sub cmdPrev_Click()


If Not adoBooks.Recordset.BOF Then
adoBooks.Recordset.MovePrevious
If adoBooks.Recordset.BOF Then
adoBooks.Recordset.MoveNext
End If
End If
End Sub

For the Next(>) button, the program codes are

Private Sub cmdNext_Click()


If Not adoBooks.Recordset.EOF Then
adoBooks.Recordset.MoveNext
If adoBooks.Recordset.EOF Then
adoBooks.Recordset.MovePrevious
End If
End If
End Sub

65
66

You might also like