DBMS Lab Manual
DBMS Lab Manual
DBMS Lab Manual
Create table
Alter table
Drop Table
Objective:
To understand and use data definition language to write query for a database
Theory:
Oracle has many tools such as SQL * PLUS, Oracle Forms, Oracle Report Writer, Oracle
Graphics etc.
SQL * PLUS: The SQL * PLUS tool is made up of two distinct parts. These are
Interactive SQL: Interactive SQL is designed for create, access and
manipulate data structures like tables and indexes.
PL/SQL: PL/SQL can be used to developed programs for different
applications.
Oracle Forms: This tool allows you to create a data entry screen along with the
suitable menu objects. Thus it is the oracle forms tool that handles data gathering and
data validation in a commercial application.
Report Writer: Report writer allows programmers to prepare innovative reports
using data from the oracle structures like tables, views etc. It is the report writer tool
that handles the reporting section of commercial application.
Oracle Graphics: Some of the data can be better represented in the form of pictures.
The oracle graphics tool allows programmers to prepare graphs using data from oracle
structures like tables, views etc.
Structured Query Language is a database computer language designed for managing data
in relational database management systems (RDBMS), and originally based upon Relational
Algebra. Its scope includes data query and update, schema creation and modification, and
data access control.
SQL was one of the first languages for Edgar F. Codd's relational model and became the
most widely used language for relational databases.
IBM developed SQL in mid of 1970’s.
Oracle incorporated in the year 1979.
SQL used by IBM/DB2 and DS Database Systems.
SQL adopted as standard language for RDBS by ASNI in 1989.
1
DATA TYPES:
1. CHAR (Size): This data type is used to store character strings values of fixed length.
The size in brackets determines the number of characters the cell can hold. The
maximum number of character is 255 characters.
2. VARCHAR (Size) / VARCHAR2 (Size): This data type is used to store variable length
alphanumeric data. The maximum character can hold is 2000 character.
3. NUMBER (P, S): The NUMBER data type is used to store number (fixed or floating
point). Number of virtually any magnitude may be stored up to 38 digits of precision.
Number as large as 9.99 * 10 124. The precision (p) determines the number of places to
the right of the decimal. If scale is omitted then the default is zero. If precision is
omitted, values are stored with their original precision up to the maximum of 38 digits.
4. DATE: This data type is used to represent date and time. The standard format is DD-
MM-YY as in 17-SEP-2009. To enter dates other than the standard format, use the
appropriate functions. Date time stores date in the 24-Hours format. By default the time
in a date field is 12:00:00 am, if no time portion is specified. The default date for a date field
is the first day the current month.
5. LONG: This data type is used to store variable length character strings containing up to
2GB. Long data can be used to store arrays of binary data in ASCII format. LONG
values cannot be indexed, and the normal character functions such as SUBSTR cannot
be applied.
6. RAW: The RAW data type is used to store binary data, such as digitized picture or
image. Data loaded into columns of these data types are stored without any further
conversion. RAW data type can have a maximum length of 255 bytes. LONG RAW
data type can contain up to 2GB.
Clauses, which are in some cases optional, constituent components of statements and
queries.
Expressions, which can produce either scalar values or tables consisting of columns and
rows of data.
Predicates which specify conditions that can be evaluated to SQL three-valued logic
(3VL) Boolean truth values and which are used to limit the effects of statements and
queries, or to change program flow.
Queries which retrieve data based on specific criteria.
Statements which may have a persistent effect on schemas and data, or which may
control transactions, program flow, connections, sessions, or diagnostics.
SQL statements also include the semicolon (";") statement terminator. Though not
required on every platform, it is defined as a standard part of the SQL grammar.
Insignificant white space is generally ignored in SQL statements and queries, making it
easier to format SQL code for readability.
1. CREATE:
Example:
SQL> CREATE TABLE Student (sno NUMBER (3), sname CHAR (10), class CHAR (5));
2. ALTER:
(a)ALTER TABLE ...ADD...: This is used to add some extra fields into existing
relation.
Syntax: ALTER TABLE relation_name ADD (new field_1 data_type(size), new field_2
data_type(size),..);
3
Syntax: ALTER TABLE relation_name RENAME COLUMN (OLD field_name) to
(NEW field_name);
3. DROP TABLE: This is used to delete the structure of a relation. It permanently deletes
the records in the table.
Experiment No:2
Objective :
To understand the different issues involved in the design and implementation of a
database system
To understand and use data manipulation language to query, update, and manage a
database
Theory :
DATA MANIPULATION LANGUAGE (DML): The Data Manipulation Language
(DML) is used to retrieve, insert and modify database information. These commands will be
used by all database users during the routine operation of the database. Let's take a brief look
at the basic DML commands:
1. INSERT INTO: This is used to add records into a relation. These are three type of
INSERT INTO queries which are as
a) Inserting a single record
4
b) Inserting a single record
Example: SQL>INSERT INTO std SELECT sno,sname FROM student WHERE name = ‘Ramu‘;
3. DELETE-FROM: This is used to delete all the records of a relation but it will retain the
structure of that relation.
5. TRUNCATE: This command will remove the data permanently. But structure will not be
removed.
5
Difference between Truncate & Delete:-
By using truncate command data will be removed permanently & will not get back where as
by using delete command data will be removed temporally & get back by using roll back
command.
By using delete command data will be removed based on the condition where as by using
truncate command there is no condition.
Truncate is a DDL command & delete is a DML command.
DEPTNO DNAME
10 ACCOUNTING
20 RESEARCH
30 SALES
3. SELECT - FROM -WHERE: This query is used to display a selected set of fields for a selected
set of records of a relation.
6
Experiment No:3
Creating relationship between the databases – Nested Queries & Join Queries
A Subquery or Inner query or a Nested query is a query within another SQL query and
embedded within the WHERE clause.
A subquery is used to return data that will be used in the main query as a condition to
further restrict the data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements
along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
There are a few rules that subqueries must follow −
Subqueries must be enclosed within parentheses.
A subquery can have only one column in the SELECT clause, unless multiple columns are
in the main query for the subquery to compare its selected columns.
An ORDER BY command cannot be used in a subquery, although the main query can use
an ORDER BY. The GROUP BY command can be used to perform the same function as
the ORDER BY in a subquery.
Subqueries that return more than one row can only be used with multiple value operators
such as the IN operator.
The SELECT list cannot include any references to values that evaluate to a BLOB,
ARRAY, CLOB, or NCLOB.
A subquery cannot be immediately enclosed in a set function.
The BETWEEN operator cannot be used with a subquery. However, the BETWEEN
operator can be used within the subquery.
Subqueries with the SELECT Statement
Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Now, let us check the following subquery with a SELECT statement.
SQL> SELECT *
FROM CUSTOMERS
7
WHERE ID IN (SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500) ;
This would produce the following result.
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+
Subqueries with the INSERT Statement
Subqueries also can be used with INSERT statements. The INSERT statement uses the data
returned from the subquery to insert into another table. The selected data in the subquery can be
modified with any of the character, date or number functions.
The basic syntax is as follows.
UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
Example
Assuming, we have CUSTOMERS_BKP table available which is backup of CUSTOMERS table.
The following example updates SALARY by 0.25 times in the CUSTOMERS table for all the
customers whose AGE is greater than or equal to 27.
8
SQL> UPDATE CUSTOMERS
SET SALARY = SALARY * 0.25
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE >= 27 );
This would impact two rows and finally CUSTOMERS table would have the following records.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 125.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 2125.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Subqueries with the DELETE Statement
The subquery can be used in conjunction with the DELETE statement like with any other
statements mentioned above.
The basic syntax is as follows.
This would impact two rows and finally the CUSTOMERS table would have the following
records.
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
9
+----+----------+-----+---------+----------+
Objective :
To implement different types of joins
Theory :
The SQL Joins clause is used to combine records from two or more tables in a database.
A JOIN is a means for combining fields from two tables by using values common
to each.The join is actually performed by the ‘where’ clause which combines specified rows of
tables.
Syntax:
SELECT column 1, column 2, column 3...FROM table_name1, table_name2
WHERE table_name1.column name = table_name2.columnname;
Types of Joins :
1. Simple Join
2. Self Join
3. Outer Join
Simple Join:
It is the most common type of join. It retrieves the rows from 2 tables having a common
column and is further classified into
Equi-join :
A join, which is based on equalities, is called equi-join.
Example:
Select * from item, cust where item.id=cust.id;
In the above statement, item-id = cust-id performs the join statement. It retrieves rows from
both the tables provided they both have the same id as specified by the where clause. Since the
where clause uses the comparison operator (=) to perform a join, it is said to be equijoin. It
combines the matched rows of tables. It can be used as follows:
Non Equi-join:
It specifies the relationship between columns belonging to different tables by making
use of relational operators other than’=’.
Example:
Select * from item, cust where item.id<cust.id;
Table Aliases
Table aliases are used to make multiple table queries shorted and more readable. We give an
alias name to the table in the ‘from’ clause and use it instead of the name throughout
the query.
10
Self join:
Joining of a table to itself is known as self-join. It joins one row in a table to another.
It can compare each row of the table to itself and also with other rows of the same table.
Example:
select * from emp x ,emp y where x.salary >= (select avg(salary) from x.emp
where x. deptno =y.deptno);
Outer Join:
It extends the result of a simple join. An outer join returns all the rows returned by simple join
as well as those rows from one table that do not match any row from the table. The symbol (+)
represents outer join.
The SQL Joins clause is used to combine records from two or more tables in a database. A JOIN is
a means for combining fields from two tables by using values common to each.
Consider the following two tables −
11
Table 1 − CUSTOMERS Table
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Table 2 − ORDERS Table
+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables in our SELECT statement as shown below.
+----+----------+-----+--------+
| ID | NAME | AGE | AMOUNT |
+----+----------+-----+--------+
| 3 | kaushik | 23 | 3000 |
| 3 | kaushik | 23 | 1500 |
| 2 | Khilan | 25 | 1560 |
| 4 | Chaitali | 25 | 2060 |
+----+----------+-----+--------+
Here, it is noticeable that the join is performed in the WHERE clause. Several operators can be
used to join tables, such as =, <, >, <>, <=, >=, !=, BETWEEN, LIKE, and NOT; they can all be
used to join tables. However, the most common operator is the equal to symbol.
Experiment No: 4
Objective:
To practice and implement constraints
Theory:
CONSTRAINTS:
12
Constraints are used to specify rules for the data in a table. If there is any violation between the
constraint and the data action, the action is aborted by the constraint. It can be specified when the
table is created (using CREATE TABLE statement) or after the table is created (using ALTER
TABLE statement).
1. NOT NULL: When a column is defined as NOTNULL, then that column becomes a mandatory
column. It implies that a value must be entered into the column if the record is to be accepted for
storage in the table.
Syntax:
CREATE TABLE Table_Name (column_name data_type (size) NOT NULL, );
Example:
CREATE TABLE student (sno NUMBER(3)NOT NULL, name CHAR(10));
2. UNIQUE: The purpose of a unique key is to ensure that information in the column(s) is unique
i.e. a value entered in column(s) defined in the unique constraint must not be repeated across the
column(s). A table may have many unique keys.
Syntax:
CREATE TABLE Table_Name(column_name data_type(size) UNIQUE, ….);
Example:
CREATE TABLE student (sno NUMBER(3) UNIQUE, name CHAR(10));
3.CHECK: Specifies a condition that each row in the table must satisfy. To satisfy the constraint,
each row in the table must make the condition either TRUE or unknown (due to a null).
Syntax:
CREATE TABLE Table_Name(column_name data_type(size) CHECK(logical
expression), ….);
Example:
CREATE TABLE student (sno NUMBER (3), name CHAR(10),class
CHAR(5),CHECK(class IN(‘CSE’,’CAD’,’VLSI’));
4. PRIMARY KEY: A field which is used to identify a record uniquely. A column or combination
of columns can be created as primary key, which can be used as a reference from other tables. A
table contains primary key is known as Master Table.
5. FOREIGN KEY: It is a table level constraint. We cannot add this at column level. To reference
any primary key column from other table this constraint can be used. The table in which the foreign
key is defined is called a detail table. The table that defines the primary key and is referenced by
the foreign key is called the master table.
13
CREATE TABLE subject (scode NUMBER (3) PRIMARY KEY, subname
CHAR(10),fcode NUMBER(3), FOREIGN KEY(fcode) REFERENCE faculty );
Experiment No: 5
Objective:
To Create a Virtual table (Views) based on the result set of an SQL statement.
Theory:
VIEW
A view is nothing more than a SQL statement that is stored in the database with an associated
name. A view is actually a composition of a table in the form of a predefined SQL query.
A view can contain all rows of a table or select rows from a table. A view can be created from one
or many tables which depends on the written SQL query to create a view.
Views, which are a type of virtual tables allow users to do the following −
Structure data in a way that users or classes of users find natural or intuitive.
Restrict access to the data in such a way that a user can see and (sometimes) modify exactly
what they need and no more.
Summarize data from various tables which can be used to generate reports.
Creating Views
Database views are created using the CREATE VIEW statement. Views can be created from a
single table, multiple tables or another view.
14
To create a view, a user must have the appropriate system privilege according to the specific
implementation.
The basic CREATE VIEW syntax is as follows −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is an example to create a view from the CUSTOMERS table. This view would be used
to have customer name and age from the CUSTOMERS table.
Now, you can query CUSTOMERS_VIEW in a similar way as you query an actual table.
Following is an example for the same.
+----------+-----+
| name | age |
+----------+-----+
| Ramesh | 32 |
| Khilan | 25 |
| kaushik | 23 |
| Chaitali | 25 |
| Hardik | 27 |
| Komal | 22 |
| Muffy | 24 |
+----------+-----+
15
The WITH CHECK OPTION
The WITH CHECK OPTION is a CREATE VIEW statement option. The purpose of the WITH
CHECK OPTION is to ensure that all UPDATE and INSERTs satisfy the condition(s) in the view
definition.
If they do not satisfy the condition(s), the UPDATE or INSERT returns an error.
The following code block has an example of creating same view CUSTOMERS_VIEW with the
WITH CHECK OPTION.
This would ultimately update the base table CUSTOMERS and the same would reflect in the view
itself. Now, try to query the base table and the SELECT statement would produce the following
result.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Inserting Rows into a View
16
Rows of data can be inserted into a view. The same rules that apply to the UPDATE command
also apply to the INSERT command.
Here, we cannot insert rows in the CUSTOMERS_VIEW because we have not included all the
NOT NULL columns in this view, otherwise you can insert rows in a view in a similar way as you
insert them in a table.
Deleting Rows into a View
Rows of data can be deleted from a view. The same rules that apply to the UPDATE and INSERT
commands apply to the DELETE command.
Following is an example to delete a record having AGE = 22.
This would ultimately delete a row from the base table CUSTOMERS and the same would reflect
in the view itself. Now, try to query the base table and the SELECT statement would produce the
following result.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Renaming the columns of a view:-
Syntax:-
CREATE VIEW viewname AS
SELECT newcolumnname….
FROM tablename
WHERE columnname=expression_list;
Experiment No:6
17
Objective:
To create PL/SQL functions and to implement the stored procedures in SQL (Function and
Procedures).
Theory:
Introduction – PL/SQL bridges the gap between database technology and procedural
programming languages. It can be thought of as a development tool that extends the
facilities of Oracles SQL database language. Via PL/SQL you can insert, delete, update
and retrieve table data as well as writing loops or branching to another block of code.
PL/SQL Block structure-
DECLARE
Declarations of memory variables used later
BEGIN
SQL executable statements for manipulating table data.
EXCEPTIONS
SQL and/or PL.SQL code to handle errors.
END;
Displaying user Messages on the screen – Any programming tool requires a method
through which messages can be displayed to the user.
dbms_output is a package that includes a number of procedure and functions that
accumulate information in a buffer so that it can be retrieved later. These functions can
also be used to display message to the user.
put_line: put a piece of information in the buffer followed by a end of line marker. It can
also be used to display message to the user.
Setting the server output on:
The GOTO statement: The goto statement allows you to change the flow of control within a
PL/SQL Block
KEYWORDS AND THEIR PURPOSES
REPLACE: It recreates the procedure if it already exists.
PROCEDURE: It is the name of the procedure to be created.
ARGUMENT: It is the name of the argument to the procedure. Parenthesis can be omitted if
no arguments are present.
IN: Specifies that a value for the argument must be specified when calling the procedure ie.,
used to pass values to a sub-program. This is the default parameter.
OUT: Specifies that the procedure passes a value for this argument back to it‟s calling
environment after execution ie. used to return values to a caller of the sub-program.
INOUT: Specifies that a value for the argument must be specified when calling the procedure
and that procedure passes a value for this argument back to it‟s calling environment after
execution.
RETURN: It is the data type of the function‟s return value because every function must return
a value, this clause is required.
PROCEDURES
Syntax :
create or replace procedure <procedure name> (argument {in,out,inout} datatype )
{is,as} variable declaration;
constant declaration;
begin
PL/SQL subprogram body;
exception
exception PL/SQL block;
end;
FUNCTIONS
Syntax:
create or replace function <function name> (argument in datatype,……) return datatype {is,as}
variable declaration;
constant declaration;
begin
PL/SQL subprogram body;
exception
exception PL/SQL block;
end;
Tables used:
SQL> select * from ititems;
ITEMID ACTUALPRICE ORDID PRODID
--------- ----------- -------- ---------
101 2000 500 201
102 3000 1600 202
103 4000 600 202
19
PROGRAM FOR GENERAL PROCEDURE – SELECTED RECORD‘S PRICE IS
INCREMENTED BY 500 , EXECUTING THE PROCEDURE CREATED AND
DISPLAYING THE UPDATED TABLE
SQL> create procedure itsum(identity number, total number) is price number;
2 null_price exception;
3 begin
4 select actualprice into price from ititems where itemid=identity;
5 if price is null then
6 raise null_price;
7 else
8 update ititems set actualprice=actualprice+total where itemid=identity;
9 end if;
10 exception
11 when null_price then
12 dbms_output.put_line('price is null');
13 end;
14 /
Procedure created.
SQL> exec itsum(101, 500);
PL/SQL procedure successfully completed.
SQL> select * from ititems;
ITEMID ACTUALPRICE ORDID PRODID
--------- ----------- --------- ---------
101 2500 500 201
102 3000 1600 202
103 4000 600 202
PROCEDURE FOR ‗IN‘ PARAMETER – CREATION, EXECUTION
SQL> set serveroutput on;
SQL> create procedure yyy (a IN number) is price number;
2 begin
3 select actualprice into price from ititems where itemid=a;
4 dbms_output.put_line('Actual price is ' || price);
5 if price is null then
6 dbms_output.put_line('price is null');
7 end if;
8 end;
9 /
Procedure created.
SQL> exec yyy(103);
Actual price is 4000
PL/SQL procedure successfully completed.
SQL> declare
2 a number:=7;
3 begin
4 itit(a);
5 dbms_output.put_line(„The updated value is „||a);
6 end;
7 /
SQL> declare
2 total number;
3 begin
4 total:=trainfn (1001);
21
5 dbms_output.put_line('Train fare is Rs. '||total);
6 end;
7 /
Experiment No: 7
Objective:
Procedure
Object
• An object is a type of user interface element you create on a Visual Basic form by using a toolbox
control.
• In fact, in Visual Basic, the form itself is also an object.
• You can move, resize, and customize objects by setting object properties.
• A property is a value or characteristic held by a Visual Basic object, such as Caption or Fore
Color.
• Properties can be set at design time by using the Properties window or at run time by using
statements in the program code.
22
Object. Property = Value
• Where Object is the name of the object you‟re customizing. Property is the characteristic you
want to change. Value is the new property setting.
• For example,
• Examples
frmExample.Cls ' clears the form frmExample.Print "This will print on the form" 2.
CommandButton
• The Command Button control is use to create buttons with a variety of uses on a form.
23
• A command button is the most basic way to get user input while a program is running.
• By clicking a command button, the user requests that a specific action be taken in the program.
• Visual Basic terms, clicking a command button creates an event, which must be processed in your
program.
• Command Button Properties:
• Appearance Selects 3-D or flat appearance.
• Cancel Allows selection of button with Esc key (only one button on a form can have this property
True).
• Caption String to be displayed on button.
• Default Allows selection of button with Enter key (only one button on a form can have this
property True).
• Font Sets font type, style, size.
• Command Button Events:
• Click Event triggered when button is selected either by clicking on it or by pressing the access
key.
3. Label Boxes
• Label, the simplest control in the Visual Basic toolbox, displays formatted text on a user interface
form. Typical uses for the Label control include:
• Help text
• Program splash screen headings
• Formatted output, such as names, times, and dates
• Descriptive labels for other objects, including text boxes and list boxes.
• Label Properties:
• Alignment Aligns caption within border.
• Appearance Selects 3-D or flat appearance.
• AutoSize -If True, the label is resized to fit the text specified by the caption property. If False, the
label will remain the size defined at design time and the text may be clipped.
• BorderStyle Determines type of border.
• Caption String to be displayed in box.
• Font Sets font type, style, size.
• Label Events:
• Click Event triggered when user clicks on a label.
• DblClick Event triggered when user double-clicks on a label.
4. Textbox
• A Textbox is used to display information entered at design time, by a user at run-time, or assigned
within code.
• The displayed text may be edited.
• The Textbox control is one of the most versatile tools in the Visual Basic toolbox.
• This control performs two functions:
• Displaying output (such as operating instructions or the contents of a file) on a form.
• Receiving text (such as names and phone numbers) as user input.
• Text Box Properties:
1. Appearance : Selects 3-D or flat appearance.
2. BorderStyle : Determines type of border.
3. Font : Sets font type, style, size.
4. MaxLength : Limits the length of displayed text (0 value indicates unlimited length).
5. MultiLine : Specifies whether text box displays single line or multiple lines. 6. PasswordChar
:Hides text with a single character.
24
7. ScrollBars :Specifies type of displayed scroll bar(s). 8. SelLength :Length of selected text (run-
time only). 9. SelStart :Starting position of selected text (run-time only). 10.SelText :Selected text
(run-time only). 11.Tag : Stores a string expression. 12.Text :Displayed text
• Text Box Events:
1. Change :Triggered every time the Text property changes.
2. LostFocus :Triggered when the user leaves the text box. This is a good place to examine the
contents of a text box after editing.
3. KeyPress :Triggered whenever a key is pressed. Used for key trapping, as seen in last class.
5. Check Boxes
• Check boxes provide a way to make choices from a list of potential candidates.
• Some, all, or none of the choices in a group may be selected
• Check Box Properties:
• Caption :Identifying text next to box.
• Font :Sets font type, style, size.
• Value :Indicates if unchecked (0, vbUnchecked), checked (1,vbChecked), or grayed out (2,
vbGrayed).
• Check Box Events:
• Click :Triggered when a box is clicked. Value property is automatically changed by Visual Basic.
6. Option Buttons
• Option buttons provide the capability to make a mutually exclusive choice among a group of
potential candidate choices.
• Hence, option buttons work as a group, only one of which can have a True (or selected) value.
• Option Button Properties:
• Caption :Identifying text next to button.
• Font :Sets font type, style, size.
• Value :Indicates if selected (True) or not (False). Only one option button in a group can be True.
One button in each group of option buttons should always be initialized to True at design time.
7. List Boxes
• A list box displays a list of items from which the user can select one or more items.
• If the number of items exceeds the number that can be displayed, a scroll bar is automatically
added.
• List Box Properties:
1. Appearance :Selects 3-D or flat appearance.
2. List :Array of items in list box.
3. ListCount :Number of items in list.
4. ListIndex :The number of the most recently selected item in list.If no item is
selected, ListIndex = -1. 5. MultiSelect :Controls how items may be selected (0-no multiple
selection allowed, 1-multiple selection allowed, 2-group selection allowed). 6. Selected :Array with
elements set equal to True or False, depending on whether corresponding list item is selected. 7.
Sorted :True means items are sorted in 'Ascii' order, else items appear in order added. 8. Text : Text
of most recently selected item.
• List Box Events:
• Click :Event triggered when item in list is clicked.
• DblClick :Event triggered when item in list is double-clicked.Primary way used to process
selection.
• List Box Methods:
• AddItem :Allows you to insert item in list.
• Clear :Removes all items from list box.
• RemoveItem :Removes item from list box, as identified by index of item to remove.
25
• Examples
• lstExample.AddItem "This is an added item" ' adds text string to list
• lstExample.Clear ' clears the list box
• lstExample.RemoveItem 4 ' removes lstExample.List(4) from list box
8.Combo Boxes
• The combo box is similar to the list box.
• The differences are a combo box includes a text box on top of a list box and only allows selection
of one item.
• In some cases, the user can type in an alternate response.
• Combo Box Properties:
• Combo box properties are nearly identical to those of the list box, with the deletion of the
MultiSelect property and the addition of a Style property.
• Appearance Selects 3-D or flat appearance.
• List Array of items in list box portion.
• ListCount Number of items in list.
• ListIndex The number of the most recently selected item in list.If no item is
selected, ListIndex = -1.
• Sorted True means items are sorted in 'Ascii' order, else items appear in order added.
• Style Selects the combo box form.Style = 0, Dropdown combo; user can change selection.Style =
1, Simple combo; user can change selection. Style = 2,
Dropdown combo; user cannot change selection.
• Text Text of most recently selected item.
• Combo Box Events:
• Click Event triggered when item in list is clicked.
• DblClick Event triggered when item in list is double-clicked. Primary way used to
process selection.
• Combo Box Methods:
• AddItem Allows you to insert item in list.
• Clear Removes all items from list box.
• RemoveItem Removes item from list box, as identified by index of item to remove.
• Examples
• cboExample.AddItem "This is an added item" ' adds text string to list
• cboExample.Clear ' clears the combo box
• cboExample.RemoveItem 4 ' removes cboExample.List(4) from list box
26
5. Value The current position of the
scroll box (thumb) within the scroll
bar. If you set this in code, Visual
Basic moves the scroll box to the
proper position.
10.Picture Boxes
• The picture box allows you to place graphics information on a form.
• It is best suited for dynamic environments - for example, when doing animation.
• Picture boxes lie in the top layer of the form display.
• They behave very much like small forms within a form, possessing most of the same properties as
a form.
• Picture Box Properties:
1. AutoSize If True, box adjusts its size to fit the displayed graphic.
2. Font Sets the font size, style, and size of any printing done in the picture box.
3. Picture Establishes the graphics file to display in the picture box.
Picture Box Events:
Click Triggered when a picture box is clicked.
DblClick Triggered when a picture box is double-clicked.
• Example
• picExample.Picture = LoadPicture("c:\pix\sample.bmp")
11. Frames
• Frames provide a way of grouping related controls on a form. And, in the case of option buttons,
frames affect how such buttons operate.
• Option buttons within a frame work as a group, independently of option buttons in other frames.
• Option buttons on the form, and not in frames, work as another independent group.
• That is, the form is itself a frame by default.
• It is important to note that an independent group of option buttons is defined by physical location
within frames, not according to naming convention.
• That is, a control array of option buttons does not work as an independent group just because it is
a control array.
• It would only work as a group if it were the only group of option buttons within a frame or on the
form .
27
12.Shape Tool
• The shape tool can create circles, ovals, squares, rectangles, and rounded squares and rectangles.
• Colors can be used and various fill patterns are available.
Result:
Thus the study of various Visual Basic tools was done.
Experiment No: 8
Objective:
To implement the forms using front end tool and use oracle for database creation.
Procedure:
1.Create a table in sql.
2. Control Panel->All Control Panel Items->Administrative Tools->ODBC datasource->ODBC
Datasource admistrator->Add->Create new data source->Microsoft ODBC for Oracle->finish-
>Microsoft ODBC for oracle setup->give sourse name(table name),username then click ok.
3.Open Microsoft visual basic 6.0->standard exe->open new project design a form
4.Project->Component->control ->choose Microsoft ADO data control 6.0(OLEDB)->apply
Designers->choose dataenvironment,data report ok
5.Tool box adodc there drag and drop into the form.
6.Right click adodc goto properties->gerenal->2 radio button use ODBC data source name->choose
table name then ok.apply ,authentication->give user name & password->apply.goto record
source->Command Type (2nd command table),next give table name->apply.
Goto general->3rd use connection string->build->datalink properties->Microsoft OLEDB provider
for ODBC driver->next connection under 1.datasource name,2.username & password then
give test connection ok .then property page apply ok.
4.Click the text box change the property datasource name adodc1,datafield name id.
5.tool->menu editor give caption name then ok.
6.Write the coding.
7.Project ->dataenvironment->properties test connection.dataenvironment right click add
command->command1 right click->properties->give dataobject(table),table name .
Sql stamen under give command Select * from table name; give apply ok.
8.Compile and run the program.
29
30
31
32
33
Experiment No: 9
Objective:
Database triggers are procedures that are stored in the database and are implicitly
executed(fired) when the contents of a table are changed.
34
There are three action query types that you use in SQL which are INSERT, UPDATE and
DELETE. So, there are three types of triggers and hybrids that come from mixing and matching
the events and timings that fire them. Basically, triggers are classified into two main types:
After Triggers (For Triggers)
Instead Of Triggers
(i) After Triggers
These triggers run after an insert, update or delete on a table. They are not supported for views.
AFTER TRIGGERS can be classified further into three types as:
AFTER INSERT Trigger
AFTER UPDATE Trigger
AFTER DELETE Trigger
ii) Instead Of Triggers
These can be used as an interceptor for anything that anyone tried to do on our table or view. If you
define an Instead Of trigger on a table for the Delete operation, they try to delete rows, and they will
not actually get deleted (unless you issue another delete instruction from within the trigger).
INSTEAD OF TRIGGERS can be classified further into three types as:
o INSTEAD OF INSERT Trigger
o INSTEAD OF UPDATE Trigger
o INSTEAD OF DELETE Trigger
Using the various options , four types of triggers can be created:-
1. Before Statement Trigger:- Before executing the triggering statement, the trigger
action is executed.
2. Before Row Trigger:- Before modifying the each row affected by the triggering
statement and before appropriate integrity constraints, the trigger is executed if the
trigger restriction either evaluated to TRUE or was not included.’
3. After Statement Trigger:- After executing the triggering statement and applying
any deferred integrity constraints, the trigger action is executed.
4. After row Trigger:- After modifying each row affected by the triggering statement
and possibly applying appropriate integrity constraints, the trigger action is executed
for the current row if the trigger restriction either evaluates to TRUE or was not
included.
Syntax For Creating Trigger:-
35
Drop Trigger <Triggername>;
TYPES OF TRIGGERS
The various types of triggers are as follows,
These two variables retain the new and old values of the column updated in the database. The
values in these variables can be used in the database triggers for data manipulation
Sytax:
Create or replace trigger <trg_name> Before /After Insert/Update/Delete
[of column_name, column_name….]
on <table_name>
[for each row]
[when condition]
begin
---statement
end;
Drop the Created Trigger Ans:
SQL> drop trigger triggername;
Experiment No:10
Objective:
Menu Design – To Design menus using menu editor in Visual Basic.
Procedure for doing the experiment:
Create a new project in VB
In the form window place the controls like Labels , text boxes in form
Go to Tools Menu Editor or right click on the form and select Menu Editor.
In the Menu Editor dialog box enter the values for caption, name and shortcut.
Select next to add a new menu item and delete to remove a menu item.
36
To add a sub menu select the right button in the Menu Editor dialog box and then
add the sub menus caption, name and shortcut.
Use “-“ in the name field to add a separator line inside a menu. After adding all
menu items select the OK button.
Double click the menu items in the form window to add the corresponding codes.
Similarly the codes are given to the text boxes and labels.
Execute the project by selecting Run Start.
After the debugging and successful execution of the project save the project and
make an executable file(*.exe) of it using the File menu.
37
38
Experiment No: 11
Objective:
Procedure:
1 Create a new VB project as data project.
2 Right click connection1 of the data environment click the property, set the provideras Oracle
provider for OLEDB and click next then type user name as scott and password as
tiger. Check whether the connection is established using test connection button.
3 Right click connection, click the Add command for the connection1 and set database object as
table and object name as scott.emp
4 Drag command1and drop it in the data reports detail section1. Two items willappear for each
object. The first label for heading information. Move this label into page header section. The
label is used to store the actual value of the object.
5
In data report1 properties set data source data environment1 and the data member as
command1. Place a button in the form write coding to view the report.
Program:
Private Sub Command1_Click()
DataReport1.Show
End Sub
Private Sub Command2_Click()
Unload Me
End Sub
Output:
39
Experiment No: 7
Objective:
Minor Project (Application Development using Oracle/Mysql)
Procedure:
Create a database for payroll processing which request the using SQL
Establish ODBC connection
In the administrator tools open data source ODBC
Click add button and select oracle in ORA home 90,click finish
A window will appear given the data source home as oracle and select TNS source
name as lion and give the used id as SWTT
ADODC CONTROL FOR SALARY FORM:-
The above procedure must be follow except the table ,A select the table as
salary
Write appropriate Program in form each from created in VB from each from
created in VB form project.
Program:
Table created.
40
SQL>create table salary(eno number,edesig varchar(10),basic number,da number,hra number,pf
number,mc number,met number,foreign key(eno) references emp);
Table created.
Form2.Show
End Sub
End Sub
Private Sub salary_Click()
Form3.Show
End Sub
Adodc1.Recordset.AddNew
MsgBox "Record added"
End Sub
Private Sub clear_Click()
Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
Text4.Text = ""
Text5.Text = ""
41
Text6.Text = ""
End Sub
Private Sub delte_Click()
Adodc1.Recordset.Delete
MsgBox "Record Deleted"
End If
End Sub
End Sub
Private Sub main_Click()
Form1.Show
End Sub
End Sub
Text2.Text = ""
Text3.Text = ""
Text4.Text = ""
Text5.Text = ""
Text6.Text = ""
End Sub
Adodc1.Recordset.MovePrevious
End If
End Sub
Private Sub exit_Click()
Unload Me
End Sub
End Sub
End Sub
OUTPUT:
43
Result:
Thus the design and implementation of payroll processing system using SQL, VB was
successfully done.
44