CS3481 DBMS Lab Manual
CS3481 DBMS Lab Manual
AIM:
To execute and verify the Data Definition Language commands
a) CREATE TABLE COMMAND
Syntax:
Create table tablename [column name datatype (size)…… column name datatype (size)];
Description :
The create table statement is used to create a table in database
Query:
SQL> create table classa (sid number (5) primary key, sname varchar2 (10), sdept
varchar2 (10), total number (5));
Output:
Table created.
SQL> desc classa;
Name Null? Type
----------------------------------------- -------- ----------------------------
SID NOT NULL NUMBER(5)
SNAME VARCHAR2(10)
SDEPT VARCHAR2(10)
TOTAL NUMBER(5)
b) ALTER TABLE QUERY:
Used to change a table without removing it from the database.The alter table statements
can be used to
Adding new columns to the existing database:
Syntax:
Alter table table name ADD [new column name datatype (size)…new column name
datatype (size)…);
Description :
To add a column into a database
Query:
SQL> alter table classa add(grade varchar2(10));
Output:
Table altered.
SQL> desc classa;
Name Null? Type
----------------------------------------- -------- ----------------------------
SID NOT NULL NUMBER(5)
SNAME VARCHAR2(10)
SDEPT VARCHAR2(10)
TOTAL NUMBER(5)
GRADE VARCHAR2(10)
Redefine the column size:
Syntax:
Alter table tablename modify (datatype (size));
Description :
To change the data type of column.
Query:
SQL> alter table classa modify ( sname varchar2(15));
Output:
Table altered.
SQL> desc classa;
Name Null? Type
----------------------------------------- -------- ----------------------------
SID NOT NULL NUMBER(5)
SNAME VARCHAR2(15)
SDEPT VARCHAR2(10)
TOTAL NUMBER(5)
GRADE VARCHAR2(10)
Delete a Column :
Syntax:
Alter table tablename drop (column name);
Description :
To delete a column.
Query:
SQL> alter table classa drop(grade);
Output:
Table altered.
SQL> desc classa;
Name Null? Type
----------------------------------------- -------- ----------------------------
SID NOT NULL NUMBER(5)
SNAME VARCHAR2(15)
SDEPT VARCHAR2(10)
TOTAL NUMBER(5)
c) RENAME TABLE:
Syntax:
Rename table_name1 to table_name2;
Description:
To rename a table.
Query:
SQL>rename classa to classb;
Output:
Table renamed.
SQL> desc classb;
Name Null? Type
----------------------------------------- -------- ----------------------------
SID NOT NULL NUMBER(5)
SNAME VARCHAR2(15)
SDEPT VARCHAR2(10)
TOTAL NUMBER(5)
6. DEFAULT CONSTRAINT:
Syntax:
CREATE Table table_name(col1 datatype(size), col2 datatype(size),default value));
Description:
The default constraint is used to insert a default value into a column.
Query:
SQL>CREATE Table ytre(regno number(5),name char(10),age number default 18);
Ouput:
SQL> desc ytre;
Name Null? Type
----------------------------------------- -------- ----------------------------
NO NUMBER(5)
NAME CHAR(20)
AGE NUMBER(5)
RESULT:
Thus the Data Definition Language commands (create, alter, drop) are studied and
executed successfully and output was verified.
Ex.No:1(b) DATA MANIPULATION LANGUAGE
AIM:
To execute and verify Data Manipulation Language commands (select, insert, update and
delete).
1. INSERT:
(a) To insert one data:
Syntax:
Insert into table name [(column name…..n column name)] values (expression…);
Description:
Adding data to a database is accomplished by SQL insert statements.
Query:
SQL>insert into cust13 values('sairam',145,'kanchipuram',9000,’SBI’,'kanchipuram’') ;
Output:
1 row created
SQL> select * from cust13;
CNAME ACC ADDR BAL BNAME BCITY
---------- ---------- -------------------- ---------- ---------- ------------------
Sairam 145 kanchipuram 9000 SBI kanchipuram
(b) UPDATE:
Syntax:
Update table name set column name=expression, column name=expression…where
column name=expression;
Description:
SQL provides the ability to modify existing data using update statements
Query:
SQL> update classa set total=400 where sid='5';
Output:
1 row updated.
SQL> select * from classa;
SID SNAME SDEPT TOTAL
---------- ---------- ---------- ---------------------
2 aarthi cse 600
3 sakthi it 500
4 vino ece 900
5 ezhil eee 400
6 kalpana it 300
c) DELETE:
Syntax:
Delete from table name where (condition);
Description:
Rows are removed from tables through the use of delete statement.The where clause is
optional. If it is not specified, all rows in selected table are removed.
Query:
SQL> delete from classa where sid='5';
Output:
1 row deleted.
SQL> select * from classa;
SID SNAME SDEPT TOTAL
---------- ---------- ---------- -------------------
2 aarthi cse 600
3 sakthi it 500
4 vino ece 900
6 kalpana it 300
d) SELECT:
Syntax:
Select * from table name [where conditions, group by column-list having conditions,
order by column-names];
Description:
Select query is used for data retrieval
Query:
To retrieve tuples in a table using select query:
SQL> select * from classa;
SID SNAME SDEPT TOTAL
---------- ---------- ---------- ----------
2 aarthi cse 600
3 sakthi it 500
4 vino ece 900
6 kalpana it 300
Retriving specific columns:
SQL> select sid,sname from classa;
SID SNAME
---------- ----------
2 aarthi
3 sakthi
4 vino
5 ezhil
Eliminating duplicates:
SQL> select distinct sdept from classa;
SDEPT
----------
cse
ece
it
Specifying condition:
SQL> select sname from classa where total>400;
SNAME
----------
aarthi
sakthi
vino
Sorting record set:
SQL> select sname from classa order by sname asc;
SNAME
----------
aarthi
ezhil
kalpana
sakthi
vino
SQL> select sname,sdept from classa order by sname asc,sdept desc;
SNAME SDEPT
---------- ----------
aarthi cse
ezhil cse
kalpana it
sakthi it
vino ece
USING SQL SPECIAL OPERATOR:
Rows with null values:
SQL> select * from classa where sdept is null;
SID SNAME SDEPT TOTAL
--------------------------------------------------------
5 ezhil cse 600
(ii) Between operator
SQL> select * from classa where total between 500 and 1000;
SID SNAME SDEPT TOTAL
---------- ---------- ---------- -------------------
2 aarthi cse 600
3 sakthi it 500
4 vino ece 900
(iii) In operator:
SQL> select * from classa where sdept in('it');
SID SNAME SDEPT TOTAL
---------- ---------- ---------- ----------------
3 sakthi it 500
6 kalpana it 300
(iv) Like operator
SQL> select * from classa where sname like 's%';
SID SNAME SDEPT TOTAL
---------- ---------- ---------- ----------
3 sakthi it 500
SQL> select * from classa where sname like '_a%';
SID SNAME SDEPT TOTAL
---------- ---------- ---------- ----------
2 aarthi cse 600
3 sakthi it 500
6 kalpana it 300
RESULT:
Thus the Data Manipulation Language commands(insert, update, delete) are studied
and executed successfully and output was verified.
Ex.No:1(c) TRANSACTION CONTROL STATEMENTS
AIM:
To execute the various transaction control statements.
COMMIT:
Syntax:
Commit;
Description:
It is used to permanently save any transaction into database.
Query:
SQL> select * from class;
NAME ID
---------- ----------
anu 1
brindha 2
chinthiya 3
divya 4
ezhil 5
fairoz 7
SQL> insert into class values('gayathri',9);
1 row created.
SQL> commit;
Output:
Commit complete.
SAVEPOINT:
Syntax:
Savepoint savapoint_name;
Description:
It is used to temporarily save a transaction so that you can rollback to that point
whenever necessary.
Query:
SQL> update class set name='hema' where id='9';
1 row updated.
SQL> savepoint A;
Savepoint created.
SQL> insert into class values('indu',11); 1 row created.
SQL> savepoint B;
Savepoint created.
SQL> insert into class values('janani',13);
1 row created.
SQL> select * from class;
NAME ID
---------- --------------------
Anu 1
Brindha 2
chinthiya 13
Divya 4
Ezhil 5
Fairoz 7
hema 9
indu 11
janani 13
9 rows selected.
ROLLBACK:
Syntax:
Rollback to savepoint_name;
Description:
It restores the database to last commited state. It is also use with savepoint command to
jump to a savepoint in a transaction
Query:
SQL> rollback toB; Rollback complete.
SQL> select * from class;
NAME ID
---------- ----------
Nu 1
Brindha 2
Chinthiya 3
Divya 4
Ezhil 5
Fairoz 7
Hema 9
Indu 1
8 rows selected.
1 SQL> rollback to A; Rollback complete.
SQL> select * from class;
NAME ID
---------- ----------
Anu 1
brindha 2
chinthiya 3
divya 4
ezhil 5
fairoz 7
hema 9
RESULT:
Thus the Transaction control statements commands (commit,rollback,savepoint) are
studied and executed successfully and output was verified.
Ex.No:2(a) SIMPLE QUERIES
AIM:
To implement and execute the simple queries in oracle database.
1.GROUP BY:
Syntax:
select column_name aggregate _function(column name)from table_name where
column_name operator value GROUP BY column_name;
Description:
The group by statement is used in conjuction with the aggregate functions to group the
result set by one or more columns.
Query:
SQL> select mark,min(name) from row123 group by mark;
Output:
MARK MIN(NAME)
---------- -------------------
23 allia
80 zeen
90 gopi
2.HAVING:
Syntax:
select column_name,aggregate_function(column_name)from
tablename GROUP BY column_name HAVING aggregate_function(column_name)>
condition;
Description:
It is used to filter data based on group functions. This is similar ‘where condition that Is
used with group functions’.
Query:
SQL>select regno,avg(mark) from row123 group by regno having avg(mark)<90 ;
Output:
REGNO AVG (MARK)
------ --------------
12 80
21 23
3. ORDER BY:
Syntax:
For Ascending Order:
select * from tablename ORDER BY column_name asc;
For Descending Order:
select * from tablename ORDER BY column_name desc;
Description:
The order by clause tuples in the result of a query to n appear in sorted order.The order
by clause arranges in ascending or descending order.
Query:
(i)For Ascending Order:
SQL> select * from row123 order by mark asc;
Output:
NAME MARK DEPT REGNO
---------- ---------- ---------- ----------
allia 23 ece 21
zeen 80 cse 12
gopi 90 mech 10
(ii)For Descending Order:
SQL> select * from row123 ORDER BY mark desc;
Output:
NAME MARK DEPT REGNO
---------- ---------- ---------- --------
gopi 90 mech 10
zeen 80 cse 12
allia 23 ece 21
RESULT:
Thus the simple queries command are studied and executed successfully and output was
verified.
Ex.No:2(b) JOIN QUERIES
AIM:
To create a database using join query.
1. INNER JOIN :
Syntax:
Select reference object 1.column name 1,,column name 2,,column name3 From table
name 1 reference object1 Inner join table name 2referenceobject 2On reference object
1.column name =reference object 2.column name;
Description:
To return rows where there is atleast one match in both table.
Query:
SQL>selecta.idno,prono,orderno,uname from userdda inner join orderlistdd b on
a.idno=b.idno;
Output:
IDNO PRONO ORDERNO UNAME
---------- ---------- ---------- ---------------------------- -
1 90 89 haritha
2 78 45 uki
2.LEFT JOIN:
Syntax:
Select reference object 1.column name 1,column name 2,column name3 From table
name 1 reference object 1left join table name 2 reference object 2 On reference object
1.column name = reference object 2.column name;
Description:
To return all rows from the left table even if there are no match in the right table
Query:
SQL>select a.idno ,prono, orderno, uname from user a left join orderlist b on a.idno =
b.idno;
Output:
IDNO PRONO ORDERNO UNAME
---------- ---------- ---------- ----------------------------------
1 90 89 haritha
2 78 45 uki
4 52 42 uj
3 56 23 koko
3. RIGHT JOIN:
Syntax:
Select reference object 1.column name 1, column name 2, column name3 From table
name 1 reference object 1right join table name 2 reference object 2 On reference object
1.column name = reference object 2.column name;
Description:
To return all rows from the right table even if there are no match in the left table
Query:
SQL>select a.idno, prono, orderno, uname from user a right join orderlist b on
a.idno=b.idno;
Output:
IDNO PRONO ORDERNO UNAME
---------- ---------- ---------- ------------------------------
1 90 89 haritha
2 78 45 uki
4. EQUIJOIN:
Syntax:
select *from table1 equi join table2 on table1.col_name=table2.col_name;
Description:
It is used to display all the matched records from both table and also displays redundant
values.
Query :
SQL>select a.idno,prono,orderno,uname from userdd a equi join orderlistdd b on
a.idno=b.idno;
Output:
IDNO UNAME FNAME LNAME IDNO ORDERNO PRONO
---------------------------------------------------------------------------------------------------------------
1 haritha haritha 1 89 90 52
2 uki uki 2 45 78 77
5. NATURAL JOIN:
Syntax:
Select *from table1 natural join table2;
Description:
It is used to display all the matched records from both tables and it avoids the redundant
values.
Query:
SQL>select *from userdd natural join orderlistdd;
Output:
IDNO UNAME FNAME ORDERNO PRONO
----------- -------------- ----------------- -------------- -------------------
1 haritha haritha 90 52
2 ukiu ki 45 85
6 .CROSS JOIN:
Syntax:
Select *from table1 cross join table2;
Description:
It produces Cartesian product of the table. The size of the Cartesian product is the number
of the rows in the first table multiplied by the number of rows in the second table.
Query:
SQL>select *from userdd cross join orderlistdd;
Output:
IDNO UNAME FNAME IDNO ORDERNO
------------------ ------------------ --------------- ------------ ----------------- ----------------
1 haritha haritha 11 89
2 ukiu ki 12 89
3 koko koko 13 89
7. OUTER JOIN:
(a)LEFT OUTER JOIN:
Syntax:
Select table1.col_name(s) from table1 left outer join table2 on table1.col_name =
table2.col_name;
Query:
SQL>select a.idno,a.uname,a.fname,prono,orderno from userdd a left outer join
orderlistdd b on a.idno=b.idno;
Output:
IDNO UNAME FNAME PRONO ORDERNO
----------- ------------------ -------------------- ------------------ --------------------
1 haritha hari 90 89
2 uki u 78 45
4 uj u 89 98
3 koko ko 67 95
AIM:
To execute various nested quories.
1. CREATE A TABLE:
Syntax:
Create table table_name2 as select*from table_name1;
Description:
To create a new table as like the table that already exist.
Query:
SQL>desc neha;
Name Null? Type
-------------------------------------------------------------------------------------------
Sno Number
Regno Number
Name Varchar(2)
SQL>create table anosha as select *from neha;
Output:
Table created.
SQL>desc anosha;
Name Null? Type
-------------------------------------------------------------------------------------
Sno Number
Regno Number
Name Varchar(2)
2. INSERTING VALUES:
Syntax:
insert into table_name2 select *from table_name1;
Description:
To insert the values from one table to another table.
Query:
SQL>select *from neha;
SNO REGNO NAME
-----------------------------------------------------------------------
1 4001 aarthi
2 4002 abirami
SQL> insert into anosha select *from nesha;
Output:
2 rows selected.
SQL>select *from sri;
Result:
Thus the various nested queries were executed and verified successfully.
Ex.No:3 VIEWS, SEQUENCES AND SYNONYMS
AIM
To execute and verify the SQL commands for Views, Sequences and Synonyms
VIEWS:
Syntax:
Create view v as <query expression>
Description:
SQL includes the ability to create stored queries that they can then be used as a basis for
other queries. These stored queries are also called views. A view is simply a derived table that is
built upon the base tables of the database. Base tables are the original database tables that
actually contain data. Views do not actually store data they are temporary tables. To define a
view, we must give the view a name and state the query that computes the view.
Query:
SQL>create view classa_b as select classa.sid, classa.sname, classa.sdept, classb.grade
from classa, classb where classa.sid=classb.id order by classa.sid;
Output:
View created
SQL> select * from classa_b;
SID SNAME SDEPT GRADE
---------- --------------- ---------- ----------
1 aarthi IT b
2 ezhil ECE b
6 sumathi ECE a
7 viji IT a
SQL> select sid, sname, sdept from classa_b where sdept='IT';
SID SNAME SDEPT
---------- -------------- ----------
1 aarthi IT
7 viji IT
RENAMING COLUMNS IN A VIEW:
Another useful feature available when creating a view is that columns can be renamed in
the CREATE VIEW statement. The new column names only apply to the views, the column
names in the base tables do not change.
Query:
SQL> create view classxy12(id,dept) as select sid,sdept from classa;
View created.
SQL> select * from classxy12;
ID DEPT
---------- ----------
1 IT
2 ECE
3 IT
4 ECE
5 IT
6 ECE
6 rows selected.
USING AGGREGATION FUNCTIONS WITH VIEWS:
Aggregate function that take a collection of value as input and return a single value .SQL
offers five built in aggregate function such as count, sum ,average, minimum and maximum.
Count function will count all the rows including duplicates or null. Sum function calculates the
sum of all values in specified column. The average function produces arithmetic mean of all the
selected values or fields. The maximum function produces max values of all the selected values
of a given fields. The minimum function produces min values of all the selected values of a
given fields.
Query:
SQL> create table course1(section varchar2(10),course varchar2(10),studentname
varchar2(10),total varchar2(10));
Table created.
SQL> select * from course1;
SECTION COURSE STUDENTNAM TOTAL
------------------------------ ------------------------ ----------
121 IT vino 500
121 IT ezhil 450
122 ECE sakthi 345
122 ECE aarthi 450
SQL>create view student_count_min(sno,count) as select min(section),count(studentname)
from course1;
View created.
SQL> select *from student_count_min;
SNO COUNT
---------- ----------
121 4
SQL> create view student_sum_avg(tot,avgtotal)as select sum(total),avg(total) from course1;
View created.
SQL> select * from student_sum_avg;
TOT AVGTOTAL
---------- ----------
1745 436.25
SQL> create view stud_max(tot) as select max(total) from course1;
View created.
SQL> select * from stud_max;
TOT
----------
500
QUERIES COMBINING VIEWS AND TABLES:
Queries can combine information from a view and a table by listing the view and the
table in the FROM clause. These queries usea join condition, just as in a multi-table query,
except the join condition will match a column in the view with a column in the table.
Query:
SQL> select * from classa;
SID SNAME SDEPT TOTAL
---------- --------------- ---------------------- ----------
2 ezhil ECE 590
6 sumathi ECE 890
SQL> select * from classa_b;
SID SNAME SDEPT GRADE
------------- --------- ----------------- ----------
2 ezhil ECE b
SQL> select classa.sid, classa.sname,classa.sdept,classa.total,classa_b.grade from classa,
classa_b where classa.sid=classa_b.sid;
SID SNAME SDEPT TOTAL GRADE
---------- -------------------------- ---------- --------------- --------------
2 ezhil ECE 590 b
DATA MANIPULATION IN VIEWS:
SQL provides the ability to modify existing data using update statements. Rows are
removed from tables through the use of delete statement. Adding data to a database is
accomplished by SQL insert statements. Select query is used for data retrieval.
Query:
SQL> Insert into classxy12 values ('8','ECE');
1 row created.
SQL> select * from classxy12;
ID DEPT
---------- ----------
1 IT
2 ECE
3 IT
4 ECE
7 IT
6 ECE
8 ECE
7 rows selected.
SQL> delete from classxy12 where dept='IT';
3 rows deleted.
SQL> select * from classXY12;
ID DEPT
---------- ----------
2 ECE
4 ECE
6 ECE
8 ECE
SQL> update classxy12 set dept='IT' where id='4';
1 row updated.
SQL> select * from classxy12;
ID DEPT
---------- ----------
2 ECE
4 IT
6 ECE
8 ECE
SQL> select * from classa;
SID SNAME SDEPT TOTAL
---------- --------------- ---------- -----------------------
2 ezhil ECE 590
6 sumathi ECE 890
SQL> select * from classb;
ID NAME GRADE
---------- ---------- ----------
1 aarthi b
2 ezhil b
NATURAL INNER JOIN IN VIEWS:
SQL uses the keyword join in the form clause to specify equi joins. The output of Select
common name from table1 natural inner join table 2; Consist of the attributes of table, followed
by attributes of table 2. The tuples in the result query would be all the tuples which have equal
value on the common attributes.
Query:
SQL> create view classab12 as select * from (classa natural inner join classb);
View created.
SQL> select * from classab12;
SID SNAME SDEPT TOTAL ID NAME GRADE
-------------------- --------------- ---------- ---------- ---------- ----------
2 ezhil ECE 590 1 aarthi b
6 sumathi ECE 890 1 aarthi b
2 ezhil ECE 590 2 ezhil b
6 sumathi ECE 890 2 ezhil b
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 entered into the table. Sequence is also somewhat similar to
AUTO_INCREMENT but its has some extra features.
Query:
SQL> select * from class;
NAME ID
---------- ----------------------
anu 1
brindha 2
chinthiya 3
divya 4
ezhil 5
fairoz 7
hema 9
8 rows selected.
Create synonym:
SQL> create synonym c1 for class;
Synonym created.
SQL> insert into c1 values ('kalai', 20);
1 row created.
SQL> select * from class;
NAME ID
-------------- -------------
Anu 1
brindha 2
chinthiya 3
divya 4
ezhil 5
fairoz 7
hema 9
kalai 20
8 rows selected.
SQL> select * from c1;
NAME ID
---------- ----------
anu 1
brindha 2
chinthiya 3
divya 4
ezhil 5
fairoz 7
hema 9
kalai 2
8 rows selected.0
SQL> insert into class values('Manu',21); 1 row created.
SQL> select * from c1;
NAME ID
----------- ---------------
anu 1
brindha 2
chinthiya 3
divya 4
ezhil 5
fairoz 7
5
hema 9
Kalai 2
Manu 21
22
9 rows selected.
20
Drop Synonym:
SQL> drop synonym c1;
Synonym dropped.
SQL> select * from c1; select * from c1
* ERROR at line 1:
ORA-00942: table or view does not xist
SEQUENCES:
Oracle provides the capability to generate sequences of unique numbers, and they are
called sequences. Just like tables, views, indexes, and synonyms, a sequence is a type of
database object. Sequences are used to generate unique, sequential integer values that are used
as primary key values in database tables. The sequence of numbers can be generated in either
ascending or descending order.
Query:
Creation of table:
SQL> create table class(name varchar(10),id number(10)); Table created.
Insert values into table:
SQL> insert into class values('&name',&id); Enter value for name: anu
Enter value for id: 1
old 1: insert into class values('&name',&id)
new 1: insert into classvalues('anu',1)
1 row created.
SQL> /
Enter value for name: brindha
Enter value for id: 02
old 1: insert into class values('&name',&id)
new 1: insert into class values('brindha',02)
1 row created.
SQL> /
Enter value for name: chinthiya
Enter value for id: 03
old 1: insert into class values('&name',&id)
new 1: insert into class values('chinthiya',03)
1 row created.
SQL> select * from class;
NAME ID
--------- ----------
Anu 1
Brindha 2
Chinthiya 3
Create Sequence:
SQL> create sequence s_1
start with 4
increment by 1
maxvalue 100
cycle;
Sequence created.
SQL> insert into class values('divya',s_1.nextval); 1 row created.
SQL> select * from class;
NAME ID
---------- ----------
anu 1
brindha 2
chinthiya 3
divya 4
Alter Sequence:
SQL> alter sequence s_1
2 increment by 2;
Sequence altered.
SQL> insert into class values('fairoz',s_1.nextval); 1 row created.
SQL> select * from class;
NAME ID
---------- ----------
anu 1
brindha 2
chinthiya 3
divya 4
ezhil 5
Drop Sequence:
SQL> drop sequence s_1;
Sequence dropped.
RESULT:
Thus the SQL commands for View, sequence and synonyms has been executed
successfully and output was verified.
Ex.No:4(a) IMPLICIT CURSORS
AIM:
To write a PL/SQL code block to implicit cursors.
PROGRAM:
Begin
Update emp_information SET emp_dept=’web developer’
Where emp_name=’saulin’;
IF SQL%FOUND THEN
Dbms_output.put_line(‘UPDATE – IF FOUND’);
END IF
IF SQL%NOTFOUND THEN
Dbms_output.put_line(‘NOT UPDATE – IF NOT FOUND’);
END IF
IF SQL%ROWCOUNT > 0 THEN
Dbms_output.put_line(‘SQL%ROWCOUNT||’ROWS UPDATED’);
ELSE
Dbms_output.put_line(‘NO ROW UPDATE FOUND’);
END;
/
OUTPUT:
UPDATE – IF FOUND
1 ROW UPDATED
PL/SQL PROCEDURE SUCCESSFULLY COMPLETED.
RESULT:
Thus the PL/SQL program for implicit cursor was verified successfully.
Ex.No:4(b) EXPLICIT CURSOR
AIM:
To write the PL/SQL program to explicit cursor.
PROGRAM:
Declare
Cursor er IS select eid, name from emp orderby name;
Id emp.eid%type;
Ename emp.name%type;
Begin
OPEN er;
LOOP
FETCH er into id,ename;
EXIT when er%notfound;
Dbms_output.put_line(id||ename);
End loop
Close er;
END;
/
OUTPUT:
1 || parimal
2 || preet
PL/SQL procedurce successfully completed.
RESULT:
Thus the PL/SQL program for implicit cursor was verified successfully.
Ex.No:5(a) FIBONACCI SERIES
AIM:
To write a PL/SQL code block program to generate the Fibonacci Series
ALGORITHM:
STEP-1: Start the program.
STEP-2: Declare the variables.
STEP-3: Initialize a=0 and b=1
STEP-4: Get the value of n
STEP-5: Incrementing the value of iupto n in loop.
STEP-6: Display the value of a result.
STEP-7: Stop the program.
PROGRAM:
declare
a number(10);
b number(10);
c number(10);
n number(10);
i number(10);
begin
a:=0;
b:=1;
i:=0;
n:=5;
dbms_output.put_line(a);
dbms_output.put_line(b);
while(n-2>i)
loop
c:=a+b;
dbms_output.put_line(c);
a:=b;
b:=c;
i:=i+1;
end loop;
end;
OUTPUT:
SQL> /
Enter value for n: 5
old 11: n:=&n;
new 11: n:=5;
0
1
1
2
3
PL/SQL procedure successfully completed.
RESULT:
Thus the PL/SQL for generating the Fibonacci series was verified successfully.
Ex.No:5(b) PALINDROME
AIM:
To write a procedure for Palindrome of the given String.
ALGORITHM:
STEP-1: Start
STEP-2: Declare the variables used in the program
STEP-3: Under the begin section in for loop check the palindrome
STEP-4: End loop
STEP-5: Display the output by using the output syntax
STEP-6: Stop.
PROGRAM:
declare
g varchar2(20);
r varchar2(20);
begin
g:='&g';
dbms_output.put_line('the given text='||g);
for i in reverse 1..length(g)loop
r:=r||substr(g,i,1);
end loop;
dbms_output.put_line('the reserved text:'||r);
if r=g then
dbms_output.put_line('the given text is palindrome');
else
dbms_output.put_line('the given text is not palindrome');
end if;
end;
/
OUTPUT:
SQL> @pal;
Enter value for g: madam
old 5: g:='&g';dbms_output.put_line('the given text='||g);
new 5: g:='madam';dbms_output.put_line('the given text='||g);
the given text=madam
the reserved text:madam
the given text is palindrome
PL/SQL procedure successfully completed.
RESULT:
Thus the PL/SQL for Palindrome of the given String was verified successfully.
Ex.No:5(c) STUDENT DATABASE
AIM:
To write a procedure for Student Database.
ALGORITHM:
STEP-1: Start the program.
STEP-2: Declare the variables.
STEP-3: Initialize a=0 and b=1.
STEP-4: calculate the total of studented
STEP-5: Display the value of a total, avg, result.
STEP-6: Stop the program.
7 rows selected.
RESULT:
Thus the PL/SQL for students database was verified successfully.
Ex.No:5(d) SUM OF N NUMBERS
AIM:
To write a PL/SQL code block program to create functions for finding sum of n
numbers.
ALGORITHM:
STEP-1: Start the program.
STEP-2: Declare the variables.
STEP-3: Initialize a=0 and b=1.
STEP-4: Get the values of a and b by incrementing value of bupto c and in c.
STEP-5: Display the value of a result.
STEP-6: Stop the program.
PROGRAM:
declare
a number(5):=0;
b number(5);
c number(5);
begin
c:='&c';
for b in 1..c loop
a:=a+b;
end loop;
dbms_output.put_line(‘sum of n numbers =’||a);
end;
/
OUTPUT:
Enter value for c: 3
old 6: c:='&c';
new 6: c:='6';
sum of n numbers =6
RESULT:
Thus the PL/SQL program for sum of n numbers was verified successfully.
Ex.No:5(e) FACTORIAL
AIM:
To write the PL/SQL program to find the factorial of a number.
ALGORITHM:
STEP-1: Start
STEP-2: Declare the variables used in program
STEP-3: Under the begin section assume i=1 and j upto the given number
STEP-4: End loop
STEP-5: Display the output by using the output format
STEP-6: Stop
PROGRAM:
SQL> set serveroutput on
SQL> declare
i number(5);
j number (5);
f number(10);
begin
i:=&i;
f:=1;
for j in 1..i
loop
f:=f*j;
end loop;
dbms_output.put_line(f);
end;
/
OUTPUT:
Enter value for i: 3
old 6: i:=&i;
new 6: i:=3;
6
PL/SQL procedure successfully completed.
RESULT:
Thus the PL/SQL for finding the factorial of a number was verified successfully.
Ex.No:5(f) AREA OF A CIRCLE
AIM:
To the write the PL/SQL program to find the area of a circle.
ALGORITHM:
STEP-1: Start
STEP-2: Declare the variable used in the program under the declare section
STEP-3: Begin the program by assuming the radius to 1
STEP-4: Under the while loop declare area as pi*pow(radius,2);
STEP-5: End loop
STEP-6: Stop
PROGRAM:
DECLARE
area NUMBER(6, 2) ;
perimeter NUMBER(6, 2) ;
radius NUMBER(1) := 3;
pi CONSTANT NUMBER(3, 2) := 3.14;
BEGIN
area := pi * radius * radius;
perimeter := 2 * pi * radius;
dbms_output.Put_line('Area = ' || area);
dbms_output.Put_line(' Perimeter = ' || perimeter);
END;
OUTPUT
Area = 28.26
Perimeter = 18.84
PL/SQL procedure successfully completed.
RESULT:
Thus the PL/SQL for finding the area of circle was verified successfully
Ex.No:5(g) BIGGEST OF THREE NUMBER
AIM:
To write the PL/SQL program to find the biggest of three number
ALGORITHM:
STEP-1: Start
STEP 2: Under the declare section declare the variables used in program
STEP-3: In begin section get the values of variables
STEP-4: Check the number with given condition
STEP-5: End if
STEP-6: Stop.
PROGRAM:
declare
a number;
b number;
c number;
begin
a:=&a;
b:=&b;
c:=&c;
if a=b and b=c and c=a then
dbms_output.put_line('ALL ARE EQUAL');
else if a>b and a>c then
dbms_output.put_line('A IS GREATER');
else if b>c then
dbms_output.put_line('B IS GREATER');
else
dbms_output.put_line('C IS GREATER');
end if;
end;
/
OUTPUT:
SQL> @ GREATESTOF3.sql
Enter value for a: 8
old 6: a:=&a;
new 6: a:=8;
Enter value for b: 9
old 7: b:=&b;
new 7: b:=9;
Enter value for c: 7
old 8: c:=&c;
new 8: c:=7;
B IS GREATER
PL/SQL procedure successfully completed.
RESULT:
Thus the PL/SQL for finding the biggest of a number was verified successfully.
Ex.No:6 FUNCTION
AIM:
To execute the functions in SQL.
(1) NUMBER FUNCTIONS:
(a) CEIL:
Syntax:
select ceil(value) “heading” from dual;
Description:
This function is used to round off the number to the nearest value.
Query:
SQL> select ceil(15.7) ‘ceiling’ from dual;
Output:
Ceiling
------------
16
(b) FLOOR:
Syntax:
select floor(value) “heading” from dual;
Description:
This function will return the value leaving the numbers after the decimal point
Query:
SQL>select floor (15.7) “Floor” from dual;
OUTPUT:
Floor
-----------
15
(c) MOD:
Syntax:
select mod (value1,value2) “heading” from dual;
Description:
This function will perform the modulo(%) operation of the given two numbers.
Query:
SQL>select mod(26,11) “modulo” from dual;
Output:
Modulo
----------
4
(d) ROUND:
Syntax:
select round(value,limit) from dual;
Description:
This function will round of the value after the decimal point.
Query:
SQL>select round(54.339,2) “Round” from dual;
Output:
Round
-----------
54.34
(e)TRUNCATE:
Syntax:
Select trunc(decimal_value) from dual;
Description:
This function will display the number before the decimal point.
Query:
SQL>Select trunc(54.339) “truncate” from dual;
Output:
Truncate
------------
54
(2) CHARACTER FUNCTIONS:
(a) CHR:
Syntax:
Select chr(value) “heding” from dual;
Description:
This function will return the corresponding alphabet for the given ASCII value.
Query:
SQL>select chr(68)||chr(79)||chr(71) “god” from dual;
Output:
God
-------
GOD
(b) CONTACT:
Syntax:
Select concat(‘char1’, ‘char2’) from dual;
Description:
To join separate words together and display the single word obtained.
Query:
SQL>select concat(‘myth’, ‘ri’) “concat” from the dual;
Output:
Conca
---------
Mythri
(c) INITCAP:
Syntax:
Select initcap(‘sentence’) “heading” from dual;
Description:
This function will return the character with the first letter of each word in uppercase and
all the other letters in lowercase.
Query:
SQL>select initcap(‘the box’) “capitals” from dual;
Output:
Capitals
------------
The box
(d)LOWER:
Syntax:
select lower(‘word’) “heading” from dual;
Description:
This function will return all the characters in the sequence in lowercase
Query:
SQL>select lower(‘temple’) “lower” from dual;
Output:
Lower
-----------
Temple
(e)PADDING:
LPAD:
Syntax:
Select lpad (‘word’,number,‘symbol’) “heading” from dual;
Description:
This function will pad the given character or symbol to the leftside of the given word.
Query:
SQL>select lpad(‘page1’,15, ‘*.’) “LPAD example” from dual;
Output:
LPAD example
-------------
*.*.*.*.*.page1
RPAD:
Syntax:
Select rpad(‘char1’,number, ‘char2’) “heading” from dual;
Description:
This function will pad the given character or symbol to the rightside of the given word.
Output:
RPAD example
------------
page1*.*.*.*.*.
(f)LTRIM:
Syntax:
Select ltrim(‘char1’, ‘set’) “heading” from dual;
Description:
This function will remove the characters from the left of the characters that appear in the
set remod;
Query:
SQL>select ltrim(‘xyxyxyLAST WORD’, ‘xy’) “LTRIM example” FROM DUAL;
Output:
LTRIM example
------------
LAST WORD
(g)REPLACE:
Syntax:
select replace (‘char’, ‘search string’, ‘replace string’) “heading” FROM DUAL;
Description:
This function will return the characters with every occurance of search string the replaced
with the replacement string
Query:
SQL>select replace (‘jack and jue’, ‘j’, ‘bl’) “changes” FROM DUAL;
Output:
Changes
------------
Black and blue
(h)SUBSTR:
Syntax:
Select substr(‘char’,m,n) “heading FROM DUAL;
Query:
SQL>select substr(,’information’,3,4) from dual;
Output:
Subs
---------
Form
(i)TRANSLATE:
Syntax:
select translate(‘char’, ‘from’, ‘to’) from dual;
Description:
This function will translate the letter from one form to another
Query:
SQL>select translate(‘element’, ‘m’,5) from dual;
Output:
Element
(j)USER:
Syntax:
select user “heading” from dual;
Description:
This function will display the current user.
Query:
SQL>select user “user” from dual;
Output:
USER
----------
SCOTT
RESULT:
Thus the functions in SQL was executed and verified successfully.
Ex.No:7 TRIGGERS
AIM:
To execute and verify the before insert trigger , after insert trigger, before delete trigger,
after delete trigger with syntax and example.
1. BEFORE INSERT:
SQL>CREATE TRIGGER v BEFORE INSERT on ordersll or for each row
declare
v_usernamevarchar2(10);
begin
select user into v_username from dual;
new.create_date:=sysdate;
new.created_by:=v_username;
end;
Trigger created.
OUTPUT:
SQL> insert into ordersllvalues(1002,20,25,500,'01-april-2014','lak');
insert into ordersll values(1002,20,25,500,'01-april-2014','lak')
*
ERROR at line 1:
ORA-04098: trigger 'SCOTT.LAL' is invalid and failed re-validation
2. AFTER INSERT:
SQL>create trigger kkk after insert on salary
declare
k integer;
begin
select count(*) into k from salaryla;
if(k>=10) then
dbms_output.put_line('add only 2');
end if;
end;
Trigger created.
OUTPUT:
SQL> insert into salarylavalues(1001,'sara',5000) ;
1 row created.
SQL> select *from salaryla;
ENO ENAME AMOUNT
--------------------------------------------------
1001 sara 5000
3. AFTER DELETE:
SQL>create trigger juju after delete on salaryla for each row
begin
dbms_output.put_line('deletion is done');
end;
Trigger created.
OUTPUT:
SQL> delete from salaryla where eno=1;
0 rows deleted.
4. BEFORE DELETE:
SQL>Create trigger delmsg Before delete on salary For each row
Begin
Raise_application_error(-23099,’detail record may be present’);
End;
Trigger created.
OUTPUT:
Sql>delete from salary;
Delete from sal
*
Error at line 1;
Error during execution of trigger
‘241752’ del msg.
5. BEFORE UPDATE:
SQL>Create trigger updatetri
1 Begin
2 Raise_application_error(-2033,’no more deduction’);
3 End;
Trigger created.
OUTPUT:
Update set salary name=’I’;
Error:error during execution of trigger.
RESULT:
Thus the PL/SQL program to illustrate triggers are executed and the output is verified.
Ex.No: 8(a) USER DEFINE EXCEPTION HANDLING
AIM:
To write a PL/SQL program to user define exception handling.
PROGRAM:
SQL>declare
n integer:=&n
a exception;
b exception;
begin
if mod(n,2)=0 then
raise a;
else
raise b;
end if;
exception
when a then
dbms_output.put_line(‘the input is even…….’)
when b then
dbms_output.put_line(‘the input is odd…….’)
end;
/
OUTPUT:
Enter value for n: 20
Old 2: n integer:=&n;
New 2: n integer:=20;
The input is even
PL/SQL procedure successfully completed.
SQL>/
Enter value for n: 21
Old 2: n integer:=&n;
New 2: n integer:=21;
The input is odd
PL/SQL procedure successfully completed.
RESULT:
Thus the PL/SQL program for exception handling was written , executed and the output
was verified successfully.
Ex.No: 8(b) DIVIDE BY ZERO EXCEPTION HANDLING
AIM:
To write a PL/SQL program to divide by zero exception handling.
PROGRAM:
SQL> declare
l_num1 number;
l_num2 number;
begin
l_num1:=10;
l_num2:=0;
dbms_output.put_line(‘result:’||l_num1/l_num2);
exception
when zero_divide then
dbms_output.put_line(sqlcode);
dbms_output.put_line(sqlerrm);
End;
/
OUTPUT:
-1476
ORA-01476: divisor is equal to zero
PL/SQL procedure successfully completed.
RESULT:
Thus the PL/SQL program for exception handling was written , executed and the output
was verified successfully.
Ex.No:9 DATABASE DESIGN USING E-R MODEL AND NORMALIZATION
ER DIAGRAM:
Chen Notation
Chen Notation
RESULT:
Thus the ER Database design using E-R model and Normalization was implemented
successfully.
Ex.No:10 FRONT END TOOLS
AIM:
To study the front end tool Visual Basic
Here, you can see a form with the name Form1, a command button with the name
Command1, a Label with the name Label1 and a Picture Box with the name Picture1. Similarly,
when you click on the procedure box, a list of procedures associated with the object will be
displayed as shown below
Some of the procedures associated with the object Form1 are Activate, Click, DblClick
(which means Double-Click) , DragDrop, keyPress and more. Each object has its own set of
procedures. You can always select an object and write codes for any of its procedure in order to
perform certain tasks.
Private Sub Form_Load
...... { Write your code here }
End Sub
Example 1
Private Sub Form_Load ( )
Form1.show
Print “Welcome to Visual Basic tutorial”
End Sub
When you press F5 to run the program, the output screen will appear as shown below
You can also perform arithmetic calculations as shown in example 2.
Example 2
Private Sub Form_Activate ( )
Print 20 + 10
Print 20 - 10
Print 20 * 10
Print 20 / 10
End Sub
the output screen will appear as shown below
1.3. The Control Properties
Before writing an event procedure for the control to response to a user's input, you have
to set certain properties for the control to determine its appearance and how it will work with
the event procedure. You can set the properties of the controls in the properties window or at
runtime.
Figure on the right is a typical properties window for a form. You can rename the form
caption to any name that you like best. In the properties window, the item appears at the top part
is the object currently selected (in Figure 6, the object selected is Form1). At the bottom part,
the items listed in the left column represent the names of various properties associated with the
selected object while the items listed in the right column represent the states of the properties.
Properties can be set by highlighting the items in the right column then change them by typing
or selecting the options available.
For example, in order to change the caption, just highlight Form1 under the name
Caption and change it to other names. You may also try to alter the appearance of the form by
setting it to 3D or flat. Other things you can do are to change its foreground and background
color, change the font type and font size, enable or disable minimize and maximize buttons and
etc.
You can also change the properties at runtime to give special effects such as change of
color, shape, animation effect and so on. For example the following code will change the form
color to red every time the form is loaded. VB uses hexadecimal system to represent the color.
You can check the color codes in the properties windows which are showed up under
ForeColor and BackColor .
Private Sub Form_Load()
Form1.Show
Form1.BackColor = &H000000FF&
End Sub
Another example is to change the control Shape to a particular shape at runtime by
writing the following code. This code will change the shape to a circle at runtime. Later you
will learn how to change the shapes randomly by using the RND function.
Private Sub Form_Load()
Shape1.Shape = 3
End Sub
Few important points about setting up the properties.
You should set the Caption Property of a control clearly so that a user knows what to do
with that command. For example, in the calculator program, all the captions of the command
buttons such as +, - , MC, MR are commonly found in an ordinary calculator, a user should
have no problem in manipulating the buttons.
A lot of programmers like to use a meaningful name for the Name Property may be
because it is easier for them to write and read the event procedure and easier to debug or modify
the programs later. However, it is not a must to do that as long as you label your objects clearly
and use comments in the program whenever you feel necessary. T
One more important property is whether the control is enabled or not.
Finally, you must also considering making the control visible or invisible at runtime, or when
should it become visible or invisible.
2. Handling some of the common controls
2.1 The Text Box
The text box is the standard control for accepting input from the user as well as to display
the output. It can handle string (text) and numeric data but not images or pictures. String in a
text box can be converted to a numeric data by using the function Val(text). The following
example illustrates a simple program that processes the input from the user.
Example 1
Private Sub Command1_Click()
Sum = Val(Text1.Text) + Val(Text2.Text) ‘To add the values in text box 1 and text box 2
Label1.Caption = Sum ‘To display the answer on label 1
End Sub
In this program, two text boxes are inserted into the form together with a few labels. The
two text boxes are used to accept inputs from the user and one of the labels will be used to
display the sum of two numbers that are entered into the two text boxes. Besides, a command
button is also programmed to calculate the sum of the two numbers using the plus operator. The
program use creates a variable sum to accept the summation of values from text box 1 and text
box 2.The procedure to calculate and to display the output on the label is shown below. The
output is shown below
2.2 The Label
The label is a very useful control for Visual Basic, as it is not only used to provide
instructions and guides to the users, it can also be used to display outputs. One of its most
important properties is Caption. Using the syntax label.Caption, it can display text and numeric
data . You can change its caption in the properties window and also at runtime.
2.3 The Command Button
The command button is one of the most important controls as it is used to execute
commands. It displays an illusion that the button is pressed when the user click on it. The most
common event associated with the command button is the Click event, and the syntax for the
procedure is
Private Sub Command1_Click ()
Statements
End Sub
2.4 The Picture Box
The Picture Box is one of the controls that is used to handle graphics. You can load a
picture at design phase by clicking on the picture item in the properties window and select the
picture from the selected folder. You can also load the picture at runtime using the LoadPicture
method. For example, the statement will load the picture grape.gif into the picture box.
Picture1.Picture=LoadPicture ("C:\VB program\Images\grape.gif")
You will learn more about the picture box in future lessons. The image in the picture box is not
resizable.
2.5 The Image Box
The Image Box is another control that handles images and pictures. It functions almost
identically to the picture box. However, there is one major difference, the image in an Image
Box is stretchable, which means it can be resized. This feature is not available in the Picture
Box. Similar to the Picture Box, it can also use the LoadPicture method to load the picture. For
example, the statement loads the picture grape.gif into the image box.
Image1.Picture=LoadPicture ("C:\VB program\Images\grape.gif")
2.6 The List Box
The function of the List Box is to present a list of items where the user can click and
select the items from the list. In order to add items to the list, we can use the AddItem method.
For example, if you wish to add a number of items to list box 1, you can key in the following
statements
Example 2.2
Private Sub Form_Load ( )
List1.AddItem “Lesson1”
List1.AddItem “Lesson2”
List1.AddItem “Lesson3”
List1.AddItem “Lesson4”
End Sub
The items in the list box can be identified by the ListIndex property, the value of the ListIndex
for the first item is 0, the second item has a ListIndex 1, and the second item has a ListIndex 2
and so on
2.7 The Combo Box
The function of the Combo Box is also to present a list of items where the user can click
and select the items from the list. However, the user needs to click on the small arrowhead on
the right of the combo box to see the items which are presented in a drop-down list. In order to
add items to the list, you can also use the AddItem method. For example, if you wish to add a
number of items to Combo box 1, you can key in the following statements
Example 2.3
Private Sub Form_Load ( )
Combo1.AddItem “Item1”
Combo1.AddItem “Item2”
Combo1.AddItem “Item3”
Combo1.AddItem “Item4”
End Sub
2.8 The Check Box
The Check Box control lets the user selects or unselects an option. When the Check Box
is checked, its value is set to 1 and when it is unchecked, the value is set to 0. You can include
the statements Check1.Value=1 to mark the Check Box and Check1.Value=0 to unmark the
Check Box, as well as use them to initiate certain actions.
For example, the program will change the background color of the form to red when the
check box is unchecked and it will change to blue when the check box is checked. You will
learn about the conditional statement If….Then….Elesif in later lesson. VbRed and vbBlue are
color constants and BackColor is the background color property of the form.
Example 2.4
Private Sub Command1_Click()
If Check1.Value = 1 And Check2.Value = 0 Then
MsgBox "Apple is selected"
ElseIf Check2.Value = 1 And Check1.Value = 0 Then
MsgBox "Orange is selected"
Else
MsgBox "All are selected"
End If
End Sub
2.9 The Option Box
The Option Box control also lets the user selects one of the choices. However, two or
more Option Boxes must work together because as one of the Option Boxes is selected, the
other Option Boxes will be unselected. In fact, only one Option Box can be selected at one time.
When an option box is selected, its value is set to “True” and when it is unselected; its value is
set to “False”.
In the following example, the shape control is placed in the form together with six Option
Boxes. When the user clicks on different option boxes, different shapes will appear. The values
of the shape control are 0, 1, and 2,3,4,5 which will make it appear as a rectangle, a square, an
oval shape, a rounded rectangle and a rounded square respectively.
Example 2.5
Private Sub Option1_Click ( )
Shape1.Shape = 0
End Sub
Private Sub Option2_Click()
Shape1.Shape = 1
End Sub
Private Sub Option3_Click()
Shape1.Shape = 2
End Sub
Private Sub Option4_Click()
Shape1.Shape = 3
End Sub
Private Sub Option5_Click()
Shape1.Shape = 4
End Sub
Private Sub Option6_Click()
Shape1.Shape = 5
End Sub
^ Exponential 2^4=16
* Multiplication 4*3=12, (5*6))2=60
/ Division 12/4=3
Mod Modulus(return the remainder 15 Mod 4=3
from an integer division)
\ Integer Division(discards the 19\4=4
decimal places)
+ or & String concatenation "Visual"&"Basic"="Visual
Basic"
Example 4.1
Dim firstName As String
Dim secondName As String
Dim yourName As String
Private Sub Command1_Click()
firstName = Text1.Text
secondName = Text2.Text
yourName = secondName + " " + firstName
Label1.Caption = yourName
End Sub
In this example, three variables are declared as string. For variables firstName and
secondName will receive their data from the user’s input into textbox1 and textbox2, and the
variable yourName will be assigned the data by combining the first two variables. Finally,
yourName is displayed on Label1.
Example 4.2
Dim number1, number2, number3 as Integer
Dim total, average as variant
Private sub Form_Click
number1=val(Text1.Text)
number2=val(Text2.Text)
number3= val(Text3.Text)
Total=number1+number2+number3
Average=Total/5
Label1.Caption=Total
Label2.Caption=Average
End Sub
In the example above, three variables are declared as integer and two variables are
declared as variant. Variant means the variable can hold any data type. The program computes
the total and average of the three numbers that are entered into three text boxes.
5. Conditional Operators
To control the VB program flow, we can use various conditional operators. Basically,
they resemble mathematical operators. Conditional operators are very powerful tools, they let
the VB program compare data values and then decide what action to take, whether to execute a
program or terminate the program and more. These operators are shown in Table 5.1.
5.1 Logical Operators
In addition to conditional operators, there are a few logical operators which offer added
power to the VB programs. There are shown in Table 5.2.
Table 5.1: Conditional Operators Table 5.2:Logical Operators
You can also compare strings with the above operators. However, there are certain rules
to follows: Upper case letters are less than lowercase letters, "A"<"B"<"C"<"D".......<"Z" and
number are less than letters.
5.2 Using If.....Then.....Else Statements with Operators
To effectively control the VB program flow, we shall use If...Then...Else statement together
with the conditional operators and logical operators.
The general format for the if...then...else statement is
If conditions Then
VB expressions
Else
VB expressions
End If
any If..Then..Else statement must end with End If. Sometime it is not necessary to use Else.
Example:
Private Sub OK_Click()
firstnum=Val(usernum1.Text)
secondnum=Val(usernum2.Text)
If total=firstnum+secondnum And Val(sum.Text)<>0 Then
correct.Visible = True
wrong.Visible = False
Else
correct.Visible = False
wrong.Visible = True
End If
End Sub
The format of the Select Case control structure is show below:
Select Case expression
Case value1
Block of one or more VB statements
Case value2
Block of one or more VB Statements
Case value3
.
Case Else
Block of one or more VB Statements
End Select
Example 5.1
Dim grade As String
Private Sub Compute_Click( )
grade=txtgrade.Text
Select Case grade
Case "A"
result.Caption="High Distinction"
Case "A-"
result.Caption="Distinction"
Case "B"
result.Caption="Credit"
Case "C"
result.Caption="Pass"
Case Else
result.Caption="Fail"
End Select
End Sub
Example 5.2
Dim mark As Single
Private Sub Compute_Click()
'Examination Marks
mark = mrk.Text
Select Case mark
Case Is >= 85
comment.Caption = "Excellence"
Case Is >= 70
comment.Caption = "Good"
Case Is >= 60
comment.Caption = "Above Average"
Case Is >= 50
comment.Caption = "Average"
Case Else
comment.Caption = "Need to work harder"
End Select
End Sub
Example 5.3
Example 5.2 could be rewritten as follows:
Dim mark As Single
Private Sub Compute_Click()
'Examination Marks
mark = mrk.Text
Select Case mark
Case 0 to 49
comment.Caption = "Need to work harder"
Case 50 to 59
comment.Caption = "Average"
Case 60 to 69
comment.Caption = "Above Average"
Case 70 to 84
comment.Caption = "Good"
Case Else
comment.Caption = "Excellence"
End Select
End Sub
6. LOOPING
Visual Basic allows a procedure to be repeated many times as long as the processor until
a condition or a set of conditions is fulfilled. This is generally called looping . Looping is a very
useful feature of Visual Basic because it makes repetitive works easier. There are two kinds of
loops in Visual Basic, the Do...Loop and the For.......Next loop
6.1 Do Loop
The formats are
a) Do While condition
Block of one or more VB statements
Loop
b) Do
Block of one or more VB statements
Loop While condition
c) Do Until condition
Block of one or more VB statements
Loop
d) Do
Block of one or more VB statements
Loop Until condition
6.2 Exiting the Loop
Sometime we need exit to exit a loop prematurely because of a certain condition is fulfilled. The
syntax to use is known as Exit Do. You can examine Example 6.1 & 6.2 for its usage.
Example 6.1
Do while counter <=1000
num.Text=counter
counter =counter+1
Loop
* The above example will keep on adding until counter >1000.
The above example can be rewritten as
Do
num.Text=counter
counter=counter+1
Loop until counter>1000
Example 6.2
Dim sum, n As Integer
Private Sub Form_Activate()
List1.AddItem "n" & vbTab & "sum"
Do
n=n+1
Sum = Sum + n
List1.AddItem n & vbTab & Sum
If n = 100 Then
Exit Do
End If
Loop
End Sub
Explanation
In the above example, we compute the summation of 1+2+3+4+……+100. In the design
stage, you need to insert a ListBox into the form for displaying the output, named List1. The
program uses the AddItem method to populate the ListBox. The statement List1.AddItem "n" &
vbTab & "sum" will display the headings in the ListBox, where it uses the vbTab function to
create a space between the headings n and sum.
For....Next Loop
The format is:
For counter=startNumber to endNumber (Step increment)
One or more VB statements
Next
Please refer to example 6.3a,6.3b and 6.3 c for its usage.
Sometimes the user might want to get out from the loop before the whole repetitive process is
executed, the command to use is Exit For. To exit a For….Next Loop, you can place the Exit
For statement within the loop; and it is normally used together with the If…..Then… statement.
Let’s examine example 6.3
Example 6.3 a
For counter=1 to 10
display.Text=counter
Next
Example 6.3 b
For counter=1 to 1000 step 10
counter=counter+1
Next
Example 6.3 c
For counter=1000 to 5 step -5
counter=counter-10
Next
*Notice that increment can be negative
Example 6.3 d
Private Sub Form_Activate( )
For n=1 to 10
If n>6 then
Exit For
End If
Else
Print n
End If
End Sub
7. VB Built-in Functions
A function is similar to a normal procedure but the main purpose of the function is to
accept a certain input from the user and return a value which is passed on to the main program
to finish the execution. There are two types of functions, the built-in functions (or internal
functions) and the functions created by the programmers.
The general format of a function is
FunctionName (arguments)
The arguments are values that are passed on to the function.
We will learn two very basic but useful internal functions of Visual basic , i.e. the MsgBox( )
and InputBox ( ) functions.
MsgBox ( ) Function
The objective of MsgBox is to produce a pop-up message box and prompt the user to
click on a command button before he /she can continues. This format is as follows:
yourMsg=MsgBox(Prompt, Style Value, Title)
The first argument, Prompt, will display the message in the message box. The Style
Value will determine what type of command buttons appear on the message box, please refer
table 7.1 for types of command button displayed. The Title argument will display the title of the
message board.
Table 7.1: Style Values
Style Value Named Constant Buttons Displayed
0 vbOkOnly Ok button
1 vbOkCancel Ok and Cancel buttons
2 vbAbortRetryIgnore Abort, Retry and Ignore buttons.
3 vbYesNoCancel Yes, No and Cancel buttons
4 vbYesNo Yes and No buttons
5 vbRetryCancel Retry and Cancel buttons
We can use named constant in place of integers for the second argument to make the
programs more readable. In fact, VB6 will automatically shows up a list of names
constant where you can select one of them.
Example: yourMsg=MsgBox( "Click OK to Proceed", 1, "Startup Menu")
and yourMsg=Msg("Click OK to Proceed". vbOkCancel,"Startup Menu")
are the same.
yourMsg is a variable that holds values that are returned by the MsgBox ( ) function. The
values are determined by the type of buttons being clicked by the users. It has to be declared as
Integer data type in the procedure or in the general declaration section. Table 7.2 shows the
values, the corresponding named constant and buttons.
Table 7.2: Return Values and Command Buttons
Value Named Constant Button Clicked
1 vbOk Ok button
2 vbCancel Cancel button
3 vbAbort Abort button
4 vbRetry Retry button
5 vbIgnore Ignore button
6 vbYes Yes button
7 vbNo No button
To make the message box looks more sophisticated, you can add an icon besides the
message. There are four types of icons available in VB as shown in table 7.3
32 vbQuestion
48 vbExclamation
64 vbInformation
Example 7.1
Private Sub test2_Click()
Dim testMsg2 As Integer
testMsg2 = MsgBox("Click to Test", vbYesNoCancel + vbExclamation, "Test Message")
If testMsg2 = 6 Then
display2.Caption = "Testing successful"
ElseIf testMsg2 = 7 Then
display2.Caption = "Are you sure?"
Else
display2.Caption = "Testing fail"
End If
End Sub
In this example, the following message box will be displayed:
Figure 7.1
Example 3
Private Sub Form_Activate()
Print Format (8972.234, "General Number")
Print Format (8972.2, "Fixed")
Print Format (6648972.265, "Standard")
Print Format (6648972.265, "Currency")
Print Format (0.56324, "Percent")
End Sub
Now, run the program and you will get an output like the figure below:
Top of Form
Bottom of Form
String Manipulation Functions
In this lesson, we will learn how to use some of the string manipulation function such as Len,
Right, Left, Mid, Trim, Ltrim, Rtrim, Ucase, Lcase, Instr, Val, Str ,Chr and Asc.
(i)The Len Function
The length function returns an integer value which is the length of a phrase or a sentence,
including the empty spaces. The format is
Len (“Phrase”)
For example,
Len (VisualBasic) = 11 and Len (welcome to VB tutorial) = 22
The Len function can also return the number of digits or memory locations of a number that is
stored in the computer. For example,
Private sub Form_Activate ( )
X=sqr (16)
Y=1234
Z#=10#
Print Len(x), Len(y), and Len (z)
End Sub
will produce the output 1, 4 , 8. The reason why the last value is 8 is because z# is a double
precision number and so it is allocated more memory spaces.
(ii) The Right Function
The Right function extracts the right portion of a phrase. The format is
Right (“Phrase”, n)
Where n is the starting position from the right of the phase where the portion of the phrase is
going to be extracted. For example,
Right(“Visual Basic”, 4) = asic
(iii)The Left Function
The Left$ function extract the left portion of a phrase. The format is
Left(“Phrase”, n)
Where n is the starting position from the left of the phase where the portion of the phrase is
going to be extracted. For example,
Left (“Visual Basic”, 4) = Visu
(iv) The Ltrim Function
The Ltrim function trims the empty spaces of the left portion of the phrase. The format is
Ltrim(“Phrase”)
.For example,
Ltrim (“ Visual Basic”, 4)= Visual basic
(v) The Rtrim Function
The Rtrim function trims the empty spaces of the right portion of the phrase. The format
is
Rtrim(“Phrase”)
.For example,
Rtrim (“Visual Basic ”, 4) = Visual basic
(vi) The Trim function
The Ttrim function trims the empty spaces on both side of the phrase. The format is
Trim(“Phrase”)
For example,
Trim (“ Visual Basic ”) = Visual basic
(viii) The Mid Function
The Mid function extracts a substring from the original phrase or string. It takes the
following format:
Mid(phrase, position, n)
Where position is the starting position of the phrase from which the extraction process will start
and n is the number of characters to be extracted. For example,
Mid(“Visual Basic”, 3, 6) = ual Bas
(ix) The InStr function
The InStr function looks for a phrase that is embedded within the original phrase and
returns the starting position of the embedded phrase. The format is
Instr (n, original phase, embedded phrase)
Where n is the position where the Instr function will begin to look for the embedded phrase. For
example
Instr(1, “Visual Basic”,” Basic”)=8
(x) The Ucase and the Lcase functions
The Ucase function converts all the characters of a string to capital letters. On the other
hand, the Lcase function converts all the characters of a string to small letters. For example,
Ucase(“Visual Basic”) =VISUAL BASiC
Lcase(“Visual Basic”) =visual basic
(xi) The Str and Val functions
The Str is the function that converts a number to a string while the Val function converts
a string to a number. The two functions are important when we need to perform mathematical
operations.
(xii) The Chr and the Asc functions
The Chr function returns the string that corresponds to an ASCII code while the Asc
function converts an ASCII character or symbol to the corresponding ASCII code. ASCII stands
for “American Standard Code for Information Interchange”. Altogether there are 255 ASCII
codes and as many ASCII characters. Some of the characters may not be displayed as they may
represent some actions such as the pressing of a key or produce a beep sound. The format of the
Chr function is
Chr(charcode)
and the format of the Asc function is
Asc(Character)
The following are some examples:
Chr(65)=A, Chr(122)=z, Chr(37)=% , Asc(“B”)=66, Asc(“&”)=38
Top of Form
11. Creating User-Defined Functions
Creating Your Own Function
The general format of a function is as follows:
Public Function functionName (Arg As dataType,..........) As dataType
or
Private Function functionName (Arg As dataType,..........) As dataType
* Public indicates that the function is applicable to the whole project and
Private indicates that the function is only applicable to a certain module or procedure.
Example 11.1
The following program will automatically compute examination grades based on the
marks that a student obtained. The code is shown on the right.
The Code
Public Function grade(mark As Variant) As String
Select Case mark
Case Is >= 80
grade = "A"
Case Is >= 70
grade = "B"
Case Is >= 60
grade = "C"
Case Is >= 50
grade = "D"
Case Is >= 40
grade = "E"
Case Else
grade = "F"
End Select
End Function
Private Sub compute_Click()
grading.Caption = grade(mark)
End Sub
RESULT:
Thus the front end tool Visual Basic has been studied.
Ex No: 11 DATABASE DESIGN AND IMPLEMENTATION PAY ROLL PROCESSING
STEPS:
1. Create a database for payroll processing which request the using SQL
2. Establish ODBC connection
3. In the administrator tools open data source ODBC
4. Click add button and select oracle in ORA home 90, click finish
5. 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
6. ADODC CONTROL FOR SALARY FORM:-
7. The above procedure must be follow except the table , A select the table as salary
8. Write appropriate Program in form each from created in VB from each from created in VB
form project.
SQL>create table emp(eno number primary key,enamr varchar(20),age number,addr
varchar(20),DOB date,phno number(10));
Table created.
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.
TRIGGER
To calculate DA,HRA,PF,MC
SQL> create or replace trigger employ after insert on salary
declare
cursor cur is select eno,basic from salary;
begin
for cur1 in cur loop
update salary set
hra=basic*0.1,da=basic*0.07,pf=basic*0.05,mc=basic*0.03 where hra=0; 9 end loop;
end;
/
Trigger created.
PROGRAM FOR FORM 1
Private Sub emp_Click()
Form 2.Show End
Sub Private
Sub exit_Click()
Unload Me
End Sub Private
Sub salary_Click()
Form3.Show
End Sub
PROGRAM FOR FORM 2
Private Sub add_Click()
Adodc1.Recordset.AddNew MsgBox "Record added"
End Sub
Private Sub clear_Click()
Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
Text4.Text = ""
Text5.Text = ""
Text6.Text = ""
End Sub
Private Sub delte_Click()
Adodc1.Recordset.Delete
MsgBox "Record Deleted"
If Adodc1.Recordset.EOF = True
Then Adodc1.Recordset.MovePrevious
End If
End
Sub Private Sub exit_Click()
Unload Me
End Sub
Private Sub main_Click()
Form1.Show
End Sub
Private Sub modify_Click()
Adodc1.Recordset.Update
End Sub
PROGRAM FOR FORM 3
Private Sub add_Click()
Adodc1.Recordset.AddNew MsgBox "Record added"
End Sub
Private Sub
clear_Click()
Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
Text4.Text = ""
Text5.Text = ""
Text6.Text = ""
End Sub
Private Sub delte_Click()
Adodc1.Recordset.Delete MsgBox "Record Deleted"
If Adodc1.Recordset.EOF = True
Then Adodc1.Recordset.MovePrevious
End If
End Sub
Private Sub exit_Click()
Unload Me
End Sub
Private Sub main_Click()
Form1.Show
End Sub
Private Sub
modify_Click()
Adodc1.Recordset.Update
End Sub
OUTPUT:
RESULT:
Thus payroll system was designed and implemented successfully.
Ex.No:12 DESIGN AND IMPLEMENTATION OF BANKING SYSTEM
STEP:
1.Create the DB for banking system source request the using SQL
2.Establishing ODBC connection
3.Click add button and select oracle in ORA home 90 click finished
4.A window will appear give the data source name as oracle and give the user id as scott
5.Now click the test connection a window will appear with server and user name give user as
scott and password tiger Click ok
6.VISUAL BASIC APPLICATION:-
Create standard exe project in to and design ms from in request format
To add ADODC project select component and check ms ADO data control click ok
Now the control is added in the tool book
Create standard exe project in to and design ms from in request format
7.ADODC CONTEOL FOR ACCOUNT FROM:- Click customs and property window and
window will appear and select ODBC data source name as oracle and click apply as the some
window.
CREATE A TABLE IN ORACLE
SQL>create table account(cname varchar(20),accno number(10),balance number);
Table Created
SQL> insert into account values('&cname',&accno,&balance);
Enter value for cname: Mathi
Enter value for accno: 1234
Enter value for balance: 10000
old 1: insert into account values('&cname',&accno,&balance)
new 1: insert into emp values('Mathi',1234,10000) 1 row created.
SOURCE CODE FOR FORM 1
Private Sub ACCOUNT_Click()
Form2.Show
End Sub
Private Sub
EXIT_Click()
Unload Me
End Sub
Private Sub
TRANSACTION_Click()
Form3.Show
End Sub
SOURCE CODE FOR FORM 2
Private Sub CLEAR_Click()
Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
End Sub
Private Sub
DELETE_Click()
Adodc1.Recordset.DELETE MsgBox "record deleted"
Adodc1.Recordset.MoveNext If Adodc1.Recordset.EOF = True Then
Adodc1.Recordset.MovePrevious
End If
End Sub
Private Sub EXIT_Click()
Unload Me
End Sub
Private Sub
HOME_Click()
Form1.Show
End Sub
Private Sub
INSERT_Click() Adodc1.Recordset.AddNew
End Sub
Private Sub
TRANSACTION_Click()
Form3.Show
End Sub
Private Sub UPDATE_Click() Adodc1.Recordset.UPDATE MsgBox "record updated
successfully"
End Sub
SOURCE CODE FOR FORM 3
Private Sub ACCOUNT_Click()
Form2.Show
End Sub
Private Sub CLEAR_Click()
Text1.Text = ""
Text2.Text = ""
End Sub
Private Sub
DEPOSIT_Click()
Dim s As String s = InputBox("enter the amount to be deposited")
Text2.Text = Val(Text2.Text) + Val(s) A = Text2.Text MsgBox "CURRENT BALANCE IS
Rs" + Str(A) Adodc1.Recordset.Save Adodc1.Recordset.UPDATE
End Sub
Private Sub
EXIT_Click()
Unload Me
End Sub
Private Sub
HOME_Click()
Form1.Show End
Sub Private Sub
WITHDRAW_Click()
Dim s As String s = InputBox("enter the amount to be deleted")
Text2.Text = Val(Text2.Text) - Val(s) A = Text2.Text MsgBox "current balance is Rs" + Str(A)
Adodc1.Recordset.Save
Adodc1.Recordset.UPDATE
End Sub
OUTPUT:
RESULT:
Thus the banking system was designed and implemented successfully.
Ex.No:13 COLLEGE MANAGEMENT SYSTEM
AIM:
To create a mini project on college management system using Visual Basic(front end)
and SQL Oracle(back end).
DESCRIPTION:
1. College Profile: This module contains the details about the college like mission
vision, contact details and courses offered.
2.Staff Profile: This module, will contains the following details about the staff in
department wise.
3. Student Info: This module will give the complete information about the student like
their profile, marks and attendance.
4. Library: This module will give the details about the books for each department.
5. Laboratory: This module will give the information about each lab in every department.
6. Examination: This module will contains the exam time table information for both
internal and external.
7. Fees: This module will display the fees details based on the student’s register number.
8. Facilities: This module will contain the details about the facilities provided in the
College.
CODINGS:
College-Profile:
Private Sub Frame1_Click()
menu.Show
college_profile.Hide
End Sub
Student Info:
Main form
Option Explicit
Public ConStrAs String
Dim x As Integer
Public Con As New ADODB.Connection
Private Sub Command2_Click()
menu.Show
stud_info.Hide
End Sub
Private Sub Command1_Click()
rno = Text1.Text
If x = 1 Then
If Option1.Value = True Then
profile.Show
ElseIf Option2.Value = True Then
marks.Show
ElseIf Option3.Value = True Then
attendance.Show
End If
End If
End Sub
Private Sub Command3_Click ()
change_pwd.Show
End Sub
Private Sub Command4_Click ()
rno = Text3.Text
MsgBoxrno
End Sub
Private Sub Form_Load()
ConStr = "Provider=MSDAORA.1;Password=tiger;User ID=scott;Persist Security Info=True"
Con.ConnectionString = ConStr
Call Con.Open
End Sub
Private Sub Text2_LostFocus()
Dim cmd As ADODB.Command
Dim rs As New Recordset
Dim pwd As String
rs.CursorLocation = adUseClient
rs.ActiveConnection = Con
rs.Source = "select password from profile1 where regno='" & Text1.Text & "'"
Call rs.Open
pwd = rs!Password
If Text2.Text = pwd Then
x=1
Else
x=0
MsgBox "Invalid password"
End If
End Sub
Student-profile:
Option Explicit
Public ConStrAs String
Public Con As New ADODB.Connection
Private Sub Command1_Click()
profile.Hide
stud_info.Show
End Sub
Private Sub Command2_Click()
profile.Hide
menu.Show
End Sub
Private Sub Form_Load()
ConStr = "Provider=MSDAORA.1;Password=tiger;User ID=scott;Persist Security Info=True"
Con.ConnectionString = ConStr
Call Con.Open
Text7.Text = rno
Dim RSC As New Recordset
RSC.CursorLocation = adUseClient
RSC.LockType = adLockBatchOptimistic
RSC.ActiveConnection = Con
RSC.Source = "select * from profile where regno= '" & Text7.Text & "' "
Call RSC.Open
Text1.Text = RSC!regno
Text2.Text = RSC!Name
Text3.Text = RSC!f_name
Text4.Text = RSC!dob
Text5.Text = RSC!department
Text6.Text = RSC!sex
Text8.Text = RSC!address
Text9.Text = RSC!religion
Text10.Text = RSC!caste
Text11.Text = RSC!id
Text12.Text = RSC!Year
Text13.Text = RSC!hosday
Text14.Text = RSC!bustop
Text15.Text = RSC!cno
Text16.Text = RSC!doj
End Sub
Mark:
Option Explicit
Public ConStrAs String
Public Con As New ADODB.Connection
Private Sub Command2_Click()
stud_info.Show
marks.Hide
End Sub
Private Sub Form_Load()
ConStr = "Provider=MSDAORA.1;Password=tiger;User ID=scott;Persist Security Info=True"
Con.ConnectionString = ConStr
Call Con.Open
Text7.Text = rno
Dim RSC As New Recordset
RSC.CursorLocation = adUseClient
RSC.LockType = adLockBatchOptimistic
RSC.ActiveConnection = Con
RSC.Source = "select subject,iae,assignment,motivation,grade from mark where
regno= '" & Text7.Text & "' "
Call RSC.Open
Set DataGrid1.DataSource = RSC
End Sub
Attendance:
Option Explicit
Public ConStrAs String
Public Con As New ADODB.Connection
Private Sub Command2_Click()
stud_info.Show
marks.Hide
End Sub
Private Sub Form_Load()
ConStr = "Provider=MSDAORA.1;Password=tiger;User ID=scott;Persist Security Info=True"
Con.ConnectionString = ConStr
Call Con.Open
Text7.Text = rno
Dim RSC As New Recordset
RSC.CursorLocation = adUseClient
RSC.LockType = adLockBatchOptimistic
RSC.ActiveConnection = Con
RSC.Source = "select subject,total_period,attend_period,percentage from
attendance where regno= '" & Text7.Text & "' "
Call RSC.Open
Set DataGrid1.DataSource = RSC
End Sub
OUTPUT:
Login form:
Main menu:
College_profile:
Student_Info:
Change password:
Student_profile:
Student_mark:
Student_attendance:
RESULT:
Thus the College Management System was created and executed successfully.