DMBS Practical
DMBS Practical
Index
11 Mini Project
Experiment No: 1
Roll No.:
Class: TE (E&TC)
Division:
Signature:
• sudo apt-get install mysql-server-5.5 (you’ll be prompted to create a root password during the
installation. Choose a secure one and make sure you remember it, because you’ll need it later.)
Step 2 — Configuring MySQL: First, you’ll want to run the included security script. This changes
some of the less secure default options for things like remote root logins and sample users.
• sudo mysql_secure_installation
This will prompt you for the root password you created in step one. You can press ENTER to accept
the defaults for all the subsequent questions, with the exception of the one that asks if you’d like to
change the root password. You just set it in step one, so you don’t have to change it now. Next,
Initialize the MySQL data directory, which is where MySQL stores its data. How you do this
depends on which version of MySQL you’re running. You can check your version of MySQL with
the following command.
• mysql –version If you’re using a version of MySQL earlier than 5.7.6, you should initialize the
data directory by running mysql_install_db.
• sudo mysql_install_db
Step 3 — Testing MySQL: Regardless of how you installed it, MySQL should have started running
automatically. To test this, check its status.
• service mysql status
If MySQL isn’t running, you can start it with
• sudo service mysql start.
For an additional check, you can try connecting to the database using the mysqladmin tool, which
is a client that lets you run administrative commands. For JES’ITMR DBMS LABORATORY
example, this command says to connect to MySQL as root (-u root), prompt for a password (-p), and
return the version.
• mysqladmin -p -u root version
Step 4 — Log in MySQL: Use following command to log in to MySQL in terminal, write
• sudo mysql –u root –p You will be prompted for password.
After log in you can see mysql> prompt to execute queries
RDBMS Terminology:
Before we proceed to explain database system, let's revise few definitions related to database.
Database: A database is a collection of tables, with related data.
Table: A table is a matrix with data. A table in a database looks like a simple spreadsheet.
Column: One column (data element) contains data of one and the same kind, for example the
Column postcode.
PES’s Modern College of Engineering,
Department of Electronics & Telecommunication Engineering. 5
Database Management T E (E & TC)
Row: A row (tuple, entry or record) is a group of related data, for example the data of one
subscription.
Redundancy: Storing data twice, redundantly to make the system faster.
Primary Key: A primary key is unique. A key value cannot occur twice in one table. With a key,
you can find at most one row.
Foreign Key: A foreign key is the linking pin between two tables.
Compound Key: A compound key (composite key) is a key that consists of multiple columns,
because one column is not sufficiently unique.
Index: An index in a database resembles an index at the back of a book.
Referential Integrity: Referential Integrity makes sure that a foreign key value always points to an
existing row. is a fast, easy-to-use RDBMS being used for many small and big businesses. is
developed, marketed, and supported by My SQLAB, which is a Swedish company. is becoming so
popular because of many good reasons:
• Released under an open-source license. So, you have nothing to pay to use it.
• Very powerful program. It handles a large subset of the functionality of the most expensive and
powerful database packages.
• Uses a standard form of the well-known SQL data language.
•Works on many operating systems and with many languages including PHP, PERL, C, C++,
JAVA, etc.
• Works very quickly and works well even with large datasets.
• Friendly to PHP, the most appreciated language for web development.
• Supports large databases, upto 50 million rows or more in a table. The default file size limit for a
table is 4GB, but you can increase this (if your operating system can handle it) to a theoretical limit
of 8 million tera bytes (TB).
• Customizable. The open-source GPL license allows programmers to modify the software to fit their
own specific environments.
TINYINT (size) A very small integer. Signed range is from -128 to 127. Unsigned range
is from 0 to 255. The size parameter specifies the maximum display width
(which is 255)
BOOL Zero is considered as false, nonzero values are considered as true.
BOOLEAN Equal to BOOL
SMALLINT (size) A small integer. Signed range is from -32768 to 32767. Unsigned range
is from 0 to 65535. The size parameter specifies the maximum display
width (which is 255)
MEDIUMINT (size) A medium integer. Signed range is from -8388608 to 8388607. Unsigned
range is from 0 to 16777215. The size parameter specifies the maximum
display width (which is 255)
INT (size) A medium integer. Signed range is from -2147483648 to 2147483647.
Unsigned range is from 0 to 4294967295. The size parameter specifies
the maximum display width (which is 255)
INTEGER (size) Equal to INT (size)
BIGINT (size) A large integer. Signed range is from -9223372036854775808 to
9223372036854775807. Unsigned range is from 0 to
18446744073709551615. The size parameter specifies the maximum
display width (which is 255)
FLOAT (size, d) A floating point number. The total number of digits is specified in size.
The number of digits after the decimal point is specified in the d
parameter. This syntax is deprecated in MySQL 8.0.17, and it will be
removed in future MySQL versions
FLOAT(p) A floating point number. MySQL uses the p value to determine whether
to use FLOAT or DOUBLE for the resulting data type. If p is from 0 to
24, the data type becomes FLOAT (). If p is from 25 to 53, the data type
becomes DOUBLE ()
DOUBLE (size, d) A normal-size floating point number. The total number of digits is
specified in size. The number of digits after the decimal point is specified
in the d parameter
DOUBLE
PRECISION (size, d)
DECIMAL (size, d) An exact fixed-point number. The total number of digits is specified in
size. The number of digits after the decimal point is specified in the d
parameter. The maximum number for size is 65. The maximum number
for d is 30. The default value for size is 10. The default value for d is 0.
DEC (size, d) Equal to DECIMAL (size,d)
Date and Time Data Types
DATE A date. Format: YYYY-MM-DD. The supported range is from '1000-01-
01' to '9999-12-31'
DATETIME (fsp) A date and time combination. Format: YYYY-MM-DD hh:mm:ss. The
supported range is from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'.
Adding DEFAULT and ON UPDATE in the column definition to get
automatic initialization and updating to the current date and time
TIMESTAMP (fsp) A timestamp. TIMESTAMP values are stored as the number of seconds
since the Unix epoch ('1970-01-01 00:00:00' UTC). Format: YYYY-MM-
DD hh:mm:ss. The supported range is from '1970-01-01 00:00:01' UTC
to '2038-01-09 03:14:07' UTC. Automatic initialization and updating to
the current date and time can be specified using DEFAULT
CURRENT_TIMESTAMP and ON UPDATE
CURRENT_TIMESTAMP in the column definition
TIME (fsp) A time. Format: hh:mm:ss. The supported range is from '-838:59:59' to
'838:59:59'
YEAR A year in four-digit format. Values allowed in four-digit format: 1901 to
2155, and 0000. MySQL 8.0 does not support year in two-digit format.
Conclusion:
Experiment No: 2
Title: Design and develop at SQL DDL statements which demonstrate the use of
SQL objects such as Table, View, Index, Sequence and Synonym.
Roll No.:
Class: TE (E&TC)
Division:
Signature:
Experiment No. -2
Title: Design and develop at least 5 SQL DDL statements which demonstrate the use of SQL
objects such as Table, View, Index, Sequence and Synonym.
Objective: To learn all type Data Definition Language commands and their uses.
Hardware requirements: Any CPU with Pentium Processor or similar, 256 MB RAM or more, 1
GB Hard Disk or more.
Software requirements: Windows Operating System, MySQL
Theory:
Introduction to SQL:
DDL:
DDL is abbreviation of Data Definition Language. It is used to create and modify the structure of
database objects in database.
DML
DML is abbreviation of Data Manipulation Language. It is used to retrieve, store, modify, delete,
insert and update data in database.
DCL
DCL is abbreviation of Data Control Language. It is used to create roles, permissions, and
referential integrity as well it is used to control access to database by securing it.
TCL
1.Data definition Language (DDL) is used to create, rename, alter, modify, drop, replace, and
delete tables, Indexes, Views,
2.The DDL part of SQL permits database tables to be created or deleted. It also defines indexes
(keys), specify links
between tables and impose constraints between tables. The most important DDL statements in
SQL are:
Syntax
SQL Constraints
Constraints are used to limit the type of data that can go into a table.
Constraints can be specified when a table is created (with the CREATE TABLE statement) or after
the table is created (with the ALTER TABLE statement).
NOT NULL
UNIQUE
PRIMARY KEY
PES’s Modern College of Engineering,
Department of Electronics & Telecommunication Engineering. 13
Database Management T E (E & TC)
FOREIGN KEY
CHECK
DEFAULT
Syntax - Alter table add constraint constraint_name constraint_type (Attr_name) Example - Alter
table stud add constraint
Drop constraint:
Syntax
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
Syntax
To delete a column in a table, use the following syntax (notice that some database systems don't
allow deleting a column):
To change the data type of a column in a table, use the following syntax:
Syntax
The ALTER TABLE Statement is used to truncate (delete all rows) a table.
Syntax
In SQL, a view is a virtual table based on the result-set of an SQL statement.A view contains rows
and columns, just like a
real table. The fields in a view are fields from one or more real tables in the database.
Syntax
SELECT column_name(s)
FROM table_name
WHERE condition;
Syntax
1. Index in SQL is created on existing tables to retrieve the rows quickly. When there are
thousands of records in a
2. Therefore indexes are created on columns which are accessed frequently, so that the
information can be
retrieved quickly.
3. Indexes can be created on a single column or a group of columns. When a index is created, it
first sorts the
PES’s Modern College of Engineering,
Department of Electronics & Telecommunication Engineering. 15
Database Management T E (E & TC)
Syntax
ON table_name (column_name1,column_name2...);
Syntax
1. Use the CREATE SYNONYM statement to create a synonym, which is an alternative name for
a table, view,
2. Synonyms provide both data independence and location transparency. Synonyms permit
applications to
function without modification regardless of which user owns the table or view and regardless of
which
3. You can refer to synonyms in the following DML statements: SELECT, INSERT, UPDATE,
DELETE
Conclusion:
Experiment No: 3
Title: Design and develop at least 5SQL queries for suitable database application
using SQL DML statements: Insert and Select with operators and
functions.
Roll No.:
Class: TE (E&TC)
Division:
Signature:
Experiment No. -3
Title: Design and develop at least 5 SQL queries for suitable database application using SQL DML
statements: Insert and Select with operators and functions.
Objective: To learn and understand DML statements in MySQL
Hardware requirements: Any CPU with Pentium Processor or similar, 256 MB RAM or more, 1
GB Hard Disk or more.
Software requirements: Windows Operating System, MySQL
Theory:
DML command
Data Manipulation Language (DML) statements are used for managing data in database. DML
commands are not auto-committed. It means changes made by DML command are not permanent
1) INSERT command
Insert command is used to insert data into a table. Following is its general syntax,
101 Adam 15
2) UPDATE command
Update command is used to update a row of a table. Following is its general syntax,
3) Delete command
Delete command is used to delete data from a table. Delete command can also be used with
The above command will delete all the records from Student table.
SQL Functions
SQL provides many built-in functions to perform operations on data. These functions are useful
• Aggregrate Functions
• Scalar Functions
Aggregrate Functions
These functions return a single value after calculating from a group of values.Following are some
1) AVG()
Average returns average value after calculating from values in a numeric column.
e.g.
2) COUNT()
Count returns the number of rows present in the table either based on some condition or without
condition.
3) FIRST()
SQL query
4) LAST()
5) MAX()
MAX function returns maximum value from selected column of the table.
6) MIN()
MIN function returns minimum value from a selected column of the table.
7) SUM()
Scalar Functions
Scalar functions return a single value from an input value. Following are soe frequently used
Scalar Functions.
1) UCASE()
Syntax of UCASE,
Example of UCASE()
2) LCASE()
3) MID()
MID function is used to extract substrings from column values of string type in a table.
4) ROUND()
ROUND function is used to round a numeric field to number of nearest integer. It is used on
Operators:
AND and OR operators are used with Where clause to make more precise conditions for fetching
1) AND operator
Example of AND
SELECT * from Emp WHERE salary < 10000 AND age > 25
2) OR operator
OR operator is also used to combine multiple conditions with Where clause. The only difference
between AND and OR is their behaviour. When we use AND to combine two or more than two
conditions, records satisfying all the condition will be in the result. But in case of OR, atleast one
condition from the conditions specified must be satisfied by any record to be in the result.
Example of OR
SQL supports few Set operations to be performed on table data. These are used to get meaningful
3) Union
UNION is used to combine the results of two or more Select statements. However it will
eliminate duplicate rows from its result set. In case of union, number of columns and datatype
Example of UNION
UNION
4) Union All
This operation is similar to Union. But it also shows the duplicate rows.
UNION ALL
5) Intersect
Intersect operation is used to combine two SELECT statements, but it only retuns the records
which are common from both SELECT statements. In case of Intersect the number of columns
and datatype must be same. MySQL does not support INTERSECT operator.
INTERSECT
6) Minus
Minus operation combines result of two Select statements and return only those result which
belongs to first set of result. MySQL does not support INTERSECT operator.
MINUS
Conclusion:
Experiment No: 4
Title: Design and develop at least 5 SQL queries for suitable database application
using SQL DML statements: Update and Delete with operators and
functions.
Roll No.:
Class: TE (E&TC)
Division:
Signature:
Title: Design and develop at least 5 SQL queries for suitable database application using SQL DML
statements: Update and Delete with operators and functions.
Objective: To learn and understand DML statements in MySQL
Hardware requirements: Any CPU with Pentium Processor or similar, 256 MB RAM or more, 1
GB Hard Disk or more.
Software requirements: Windows Operating System, MySQL
Theory:
DML command
Data Manipulation Language (DML) statements are used for managing data in database. DML
commands are not auto-committed. It means changes made by DML command are not permanent
1) INSERT command
Insert command is used to insert data into a table. Following is its general syntax,
101 Adam 15
2) UPDATE command
Update command is used to update a row of a table. Following is its general syntax,
3) Delete command
Delete command is used to delete data from a table. Delete command can also be used with
The above command will delete all the records from Student table.
SQL Functions
SQL provides many built-in functions to perform operations on data. These functions are useful
• Aggregrate Functions
• Scalar Functions
Aggregrate Functions
These functions return a single value after calculating from a group of values.Following are some
1) AVG()
Average returns average value after calculating from values in a numeric column.
e.g.
2) COUNT()
Count returns the number of rows present in the table either based on some condition or without
condition.
3) FIRST()
SQL query
4) LAST()
5) MAX()
MAX function returns maximum value from selected column of the table.
6) MIN()
MIN function returns minimum value from a selected column of the table.
7) SUM()
Scalar Functions
Scalar functions return a single value from an input value. Following are soe frequently used
Scalar Functions.
1) UCASE()
Syntax of UCASE,
Example of UCASE()
2) LCASE()
3) MID()
MID function is used to extract substrings from column values of string type in a table.
4) ROUND()
ROUND function is used to round a numeric field to number of nearest integer. It is used on
Operators:
AND and OR operators are used with Where clause to make more precise conditions for fetching
1) AND operator
Example of AND
SELECT * from Emp WHERE salary < 10000 AND age > 25
2) OR operator
OR operator is also used to combine multiple conditions with Where clause. The only difference
between AND and OR is their behaviour. When we use AND to combine two or more than two
conditions, records satisfying all the condition will be in the result. But in case of OR, atleast one
condition from the conditions specified must be satisfied by any record to be in the result.
Example of OR
SQL supports few Set operations to be performed on table data. These are used to get meaningful
3) Union
UNION is used to combine the results of two or more Select statements. However it will
eliminate duplicate rows from its result set. In case of union, number of columns and datatype
Example of UNION
UNION
4) Union All
This operation is similar to Union. But it also shows the duplicate rows.
UNION ALL
5) Intersect
Intersect operation is used to combine two SELECT statements, but it only retuns the records
which are common from both SELECT statements. In case of Intersect the number of columns
and datatype must be same. MySQL does not support INTERSECT operator.
INTERSECT
6) Minus
Minus operation combines result of two Select statements and return only those result which
belongs to first set of result. MySQL does not support INTERSECT operator.
MINUS
Conclusion:
Experiment No: 5
Title: Design and develop at least 5 SQL queries for suitable database application
using SQL DML statements: all types of Join and Sub-Query.
Roll No.:
Class: TE (E&TC)
Division:
Signature:
Title: Design and develop at least 5 SQL queries for suitable database application using SQL DML
statements: all types of Join and Sub-Query.
Objective: To learn and understand DML statements in MySQL
Hardware requirements: Any CPU with Pentium Processor or similar, 256 MB RAM or more, 1
GB Hard Disk or more.
Software requirements: Windows Operating System, MySQL
Theory:
SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a related column
between them.
10308 10 8/5/2012
10309 20 9/9/2013
10310 30 10/9/2019
Note that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in the "Customers"
table. The relationship between the two tables above is the "CustomerID" column.Then, we can create the
following SQL statement (that contains an INNER JOIN), that selects records that have matching values in
both tables: Example: SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM
Orders INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID; and it will produce
something like this:
The ability of relational join operator is an important feature of relational systems. A join
makes it possible to select data from more than one table by means of a single statement. This
joining of tables can be done in a many ways.
Types of JOIN
1) Inner
2) Outer(left, right,full)
3) Cross
1) Inner join : - Also known as equi join.
-Statements generally compares two columns from two columns with the equivalence operator =.
-This type of join can be used in situations where selecting only those rows that have values in
common in the columns specified in the ON clause, is required.
Syntax :
(ANSI style)
SELECT<columnname1>, <columnname2> <columnNameN>
FROM <tablename1> INNER JOIN <tablename2>ON
<tablename1>.<columnname> = <tablename2>.<columnname> WHERE <condition> ORDER
BY <columnname1>;
(theta style)
PES’s Modern College of Engineering,
Department of Electronics & Telecommunication Engineering. 35
Database Management T E (E & TC)
List the employee details along with branch names to which they belong.
Emp(empno,fname,lname,dept,desig,branchno)
Branch(bname,branchno)
Select e.empno,e.fname,e.lname,e.dept, b.bname, e.desig from emp e inner join branch b on
b.branchno=e.branchno;
Select e.empno, e.fname, e.lname, e.dept, b.bname, e.desig from emp e, branch b on where
b.branchno=e.branchno;
Eg. List the customers along with the account details associated with them.
Customer(custno,fname,lname)
Acc_cust_dtls(fdno,custno)
Acc_mstr(accno,branchno,curbal)
Branch_mstr(name,branchno)
•
Select c.custno, c.fname, c.lname, a.accno,a.curbal,b.branchno,b.name from customer c inner
join acc_cust_dtls k on c.custno=k.custno inner join acc_mstr a on k.fdno=a.accno inner join
branch b on b.branchno=a.branchn
o where c.custno like „C% order by c.custno;
‟
•
Select
c.custno,
c.fname,
c.lname,
a.accno,a.curbal,b.branchno,b.name
from
customer
c,
acc_cust_dtls
k,
acc_mstr
a,
branch
b
where
c.custno=k.custno
and
k.fdno=a.accno
and
b.branchno=a.branchno and c.custno
like „C% order by c.custno;
‟
Outer Join
Outer joins are similar to inner joins, but give a little bit more flexibility when selecting data from
related tables. This type of joins can be used in situations where it is desired, to select all rows
from the
table on left( or right, or both) regardless of whether the other table has values in common & (
usually)
enter NULL where data is missing.
•
Tables
Emp_mstr(empno,fname,lname,dept)
Cntc_dtls(codeno,cntc_type,cntc_data)
Left Outer Join
List the employee details along with the contact details(if any) using left outer join.
•
Select e.empno, e.fname, e.lname, e.dept, c.cntc_type, c.cntc_data from emp_mstr e left join
cntc_dtls c on e.empno=c.codeno;
•
Select e.empno, e.fname, e.lname, e.dept, c.cntc_type, c.cntc_data from emp_mstr e cntc_dtls c
where e.empno=c.codeno(+);
Conclusion:
Experiment No: 6
Title: Write a PL/SQL block to calculate fine for a library book by accessing
borrower information from the database.
Roll No.:
Class: TE (E&TC)
Division:
Signature:
Experiment No. -6
Title: Write a PL/SQL block to calculate fine for a library book by accessing borrower information
from the database.
Problem Statement: Write a PL/SQL block of code for the following requirements:-
Schema: 1. Borrower(Rollin, Name, DateofIssue, NameofBook, Status)
2. Fine(Roll_no,Date,Amt)
3. Accept roll_no & name of book from user.
4. Check the number of days (from date of issue), if days are between 15 to 30 then fine amount will
be Rs 5per day.
5. If no. of days>30, per day fine will be Rs 50 per day & for days less than 30, Rs. 5 per day.
6. After submitting the book, status will change from I to R.
7. If condition of fine is true, then details will be stored into fine table
Objective: To learn the concept of PL/SQL.
Hardware requirements: Any CPU with Pentium Processor or similar, 256 MB RAM or more, 1
GB Hard Disk or more.
Software requirements: Windows Operating System, MySQL
Theory:
PL/SQL stands for Procedural Language extension of SQL. PL/SQL is a combination of SQL
along with
the procedural features of programming languages.It was developed by Oracle Corporation in the
early
Architecture of PL/SQL:
1. PL/SQL block
2. PL/SQL Engine
3. Database Server
PL/SQL block:
PL/SQL Engine
➢ PL/SQL engine is the component where the actual processing of the codes takes place.
➢ PL/SQL engine separates PL/SQL units and SQL part in the input (as shown in the image
below).
➢ The separated PL/SQL units will be handled with the PL/SQL engine itself.
➢ The SQL part will be sent to database server where the actual interaction with database
takes
➢ place.
➢ It can be installed in both database server and in the application server.
➢ Database Server:
➢ This is the most important component of Pl/SQL unit which stores the data.
➢ The PL/SQL engine uses the SQL from PL/SQL units to interact with the database server.
➢ It consists of SQL executor which actually parses the input SQL statements and execute the
same.
2. High Productivity
4. Full Portability
5. Tight Security
In this section, we will discuss some differences between SQL and PL/SQL
SQL PL/SQL
SQL is a single query that is used to perform PL/SQL is a block of codes that used to write
DML and DDL operations the entire program blocks/ procedure/ function,
etc.
It is declarative, that defines what needs to be PL/SQL is procedural that defines how the
done, rather than how things need to be done. things needs to be done.
Basic Syntax of PL/SQL which is a block-structured language; this means that the PL/SQL
programs are divided and written in logical blocks of code. Each block consists of three sub-parts:
Declarations :
This section starts with the keyword DECLARE. It is an optional section and defines all variables,
Executable Commands
This section is enclosed between the keywords BEGIN and END and it is a mandatory section. It
consists of the executable PL/SQL statements of the program. It should have at least one
executable line of code, which may be just a NULL command to indicate that nothing should be
executed.
Exception Handling
This section starts with the keyword EXCEPTION. This optional section contains exception(s) that
Every PL/SQL statement ends with a semicolon (;). PL/SQL blocks can be nested within other
PL/SQL
blocks using BEGIN and END. Following is the basic structure of a PL/SQL block −
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;
DECLARE
BEGIN
dbms_output.put_line(message);
END;
PL/SQL Placeholders
Placeholders are temporary storage area. PL/SQL Placeholders can be any of Variables, Constants
and
Records. Oracle defines placeholders to store data temporarily, which are used to manipulate data
during
Depending on the kind of data you want to store, you can define placeholders with a
name and a datatype. Few of the datatypes used to define placeholders are as given below.
Number (n,m) , Char (n) , Varchar2 (n) , Date , Long , Long raw, Raw, Blob, Clob, Nclob, Bfile
PL/SQL Variables
These are placeholders that store the values that can change through the PL/SQL Block.
value or DEFAULT valueis also an optional specification, where you can initialize a variable.
For example, if you want to store the current salary of an employee, you can use a variable.
DECLARE
The below example declares two variables, one of which is a not null.
DECLARE
salary number(4);
The below example declares two variables, one of which is a not null.
DECLARE
salary number(4);
The below example declares two variables, one of which is a not null.
DECLARE
salary number(4);
Conclusion:
Experiment No: 7
Title: Write a PL/SQL block to create cursor to copy contents of one table into
another. Avoid redundancy.
Roll No.:
Class: TE (E&TC)
Division:
Signature:
Title: Write a PL/SQL block to create cursor to copy contents of one table into another. Avoid
redundancy.
Problem Statement: Cursors: (All types: Implicit, Explicit, Cursor FOR Loop, Parameterized
Cursor) Write a PL/SQL block of code using parameterized Cursor, that will merge the data available
in the newly created table N_RollCall with the data available in the table O_RollCall. If the data in
the first table already exist in the second table then that data should be skipped.
Objective: To learn the concept of PL/SQL.
Hardware requirements: Any CPU with Pentium Processor or similar, 256 MB RAM or more, 1
GB Hard Disk or more.
Software requirements: Windows Operating System, MySQL
Theory:
CURSOR:-
For the processing of any SQL statement, database needs to allocate memory. This memory is
called context area. The context area is a part of PGA (Process global area) and is allocated on the
server. A cursor is associated with this work area used by for multi row queries. A cursor is a
handle or pointer to the context area. The cursor allows to process contents in the context area row
by row.
1)Implicit cursor:- Implicit cursors are defined by ORACLE implicitly. ORACLE defines
implicit cursor for every DML statements.
2) Explicit cursor:- These are user-defined cursors which are defined in the declaration section of
the PL/SQL block.
• Declaring a cursor
• Opening a cursor
• Fetching rows from an opened cursor
• Closing cursor
DECLARE
Open cursor_name;
Close cursor_name;
END;
Where,
Cursor_name : is the name of the cursor.
Select_statement : is the query that defines the set of rows to be processed by the cursor.
Open cursor_name : the cursor that has been previously declared. When cursor is opened
following things happen
i) The active set pointer is set to the first row.
ii) The value of the binding variables are examined.
Fetch statement is used to retrieve a row from the selected rows, one at a time, into PL/SQL
variables.
Close cursor_name:-When all of cursor rows have been retrieved, the cursor should be closed.
1.%FOUND: - This is Boolean attribute. It returns TRUE if the previous fetch returns a row and
false if it doesn‟t.
2. %NOTFOUND:-If fetch returns a row it returns FALSE and TRUE if it doesn‟t. This as the exit
condition for the fetch loop; is often used
3.%ISOPEN:-This attribute is used to determine whether or not the associated cursor is open. If so
it returns TRUE otherwise FALSE.
LOOP
END LOOP;
Sequence_of_statements;
END LOOP;
Implicit Cursors
PL/SQL issues an implicit cursor whenever you execute a SQL statement directly in your code, as
long as that code does not employ an explicit cursor. It is called an "implicit" cursor because you,
the developer, do not explicitly declare a cursor for the SQL statement.
If you use an implicit cursor, Oracle performs the open, fetches, and close for you automatically;
these actions are outside of your programmatic control. You can, however, obtain information about
the most recently executed SQL statement by examining the values in the implicit SQL cursor
attributes.
PL/SQL employs an implicit cursor for each UPDATE, DELETE, or INSERT statement you execute
in a program. You cannot, in other words, execute these statements within an explicit cursor, even
if you want to. You have a choice between using an implicit or explicit cursor only when you execute
a single-row SELECT statement (a SELECT that returns only one row).
In the following UPDATE statement, which gives everyone in the company a 10% raise, PL/SQL
creates an implicit cursor to identify the set of rows in the table which would be affected by the
update:
PES’s Modern College of Engineering,
Department of Electronics & Telecommunication Engineering. 48
Database Management T E (E & TC)
UPDATE employee
The following single-row query calculates and returns the total salary for a department. Once again,
PL/SQL creates an implicit cursor for this statement:
If you have a SELECT statement that returns more than one row, you must use an explicit cursor for
that query and then process the rows returned one at a time. PL/SQL does not yet support any kind
of array interface between a database table and a composite PL/SQL datatype such as a PL/SQL
table.
Even if your query returns only a single row, you might still decide to use an explicit cursor. The
implicit cursor has the following drawbacks:
The following sections explore each of these limitations to the implicit cursor.
An explicit cursor is, at least theoretically, more efficient than an implicit cursor. An implicit cursor
executes as a SQL statement and Oracle's SQL is ANSI-standard. ANSI dictates that a single-row
query must not only fetch the first record, but must also perform a second fetch to determine if too
many rows will be returned by that query (such a situation will RAISE the TOO_MANY_ROWS
PL/SQL exception). Thus, an implicit query always performs a minimum of two fetches, while an
explicit cursor only needs to perform a single fetch.
This additional fetch is usually not noticeable, and you shouldn't be neurotic about using an implicit
cursor for a single-row query (it takes less coding, so the temptation is always there). Look
out for indiscriminate use of the implicit cursor in the parts of your application where that cursor
will be executed repeatedly. A good example is the Post-Query trigger in the Oracle Forms.
Post-Query fires once for each record retrieved by the query (created from the base table block and
the criteria entered by the user). If a query retrieves ten rows, then an additional ten fetches are
needed with an implicit query. If you have 25 users on your system all performing a similar query,
your server must process 250 additional (unnecessary) fetches against the database. So, while it
might be easier to write an implicit query, there are some places in your code where you will want
to make that extra effort and go with the explicit cursor.
If an implicit SELECT statement returns more than one row, it raises the TOO_MANY_ROWS
exception. When this happens, execution in the current block terminates and control is passed to the
exception section. Unless you deliberately plan to handle this scenario, use of the implicit cursor is
a declaration of faith. You are saying, "I trust that query to always return a single row!"
It may well be that today, with the current data, the query will only return a single row. If the nature
of the data ever changes, however, you may find that the SELECT statement which formerly
identified a single row now returns several. Your program will raise an exception. Perhaps this is
what you will want. On the other hand, perhaps the presence of additional records is inconsequential
and should be ignored.
With the implicit query, you cannot easily handle these different possibilities. With an explicit query,
your program will be protected against changes in data and will continue to fetch rows without
raising execeptions
Conclusion:
Experiment No: 8
Title: To Study and implement PL/SQL programming along with Procedures and
Functions.
Roll No.:
Class: TE (E&TC)
Division:
Signature:
Title: To Study and implement PL/SQL programming along with Procedures and Functions.
Problem Statement: PL/SQL Stored Procedure and Stored Function Write a Stored Procedure
namely proc_Grade for the categorization of student. If marks scored by students in examination is
<=1500 and marks>=990 then student will be placed in distinction category if marks scored are
between 989 and900 category is first class, if marks 899 and 825 category is Higher Second Class.
Write a PL/SQL block for using procedure created with above requirement. Stud_Marks(name,
total_marks) Result(Roll,Name, Class).
Objective: To learn the concept of PL/SQL.
Hardware requirements: Any CPU with Pentium Processor or similar, 256 MB RAM or more, 1
GB Hard Disk or more.
Software requirements: Windows Operating System, MySQL
Theory:
PROCEDURE:-
A procedure is a subprogram that performs a specific action or task. A procedure has two parts.
1) The procedure specification: The procedure specification specifies the procedure name and the
parameters it accepts. It is not necessary to create a procedure that accepts parameters.
2) The procedure body: The procedure body contains the declarative section without DECLARE
keyword, the executable section and an exception section.
IS/AS
Procedure_body
Where,
Procedure_name: – is the name of the procedure to be created Argument:- is the name of the
procedure parameter
IN:-This is default mode. The value of the actual parameter is passed into the procedure. Inside the
procedure the formal parameter is considered read only.
OUT:-Any value the actual parameter has when the procedure is called ignored. Inside the
procedure ,the formal parameters are considered as write only.
FUNCTION:-
A function is a subprogram, which is used to compute values. It is similar to a procedure,
function also takes arguments and can be in different modes. Function also can be stored in
the database. It is a PL/SQL block consisting of declarative, executable and exception section.
Difference between procedure and function is that the procedure call is a PL/SQL statement
by itself, while a function call is called as a part of an expression. A function can return more
than one value using OUT parameter. A function can be called using position or named
notation.
Create [or replace] FUNCTION function_name [(argument1 [IN / OUT / IN OUT] type),
(argument2 [IN / OUT / IN OUT] type),
….]
Return return_type IS / AS
Where
Function_body
Function_name: – is the name of the function to be created
OUT:-Any value the actual parameter has when the procedure is called ignored.
Inside the procedure ,the formal parameters are considered as write only.
INOUT:-this mode is combination of IN and OUT
Syntax :
Drop function<function_name>;
Conclusion:
Experiment No: 9
Title: Write a PL/SQL block to create trigger on Library table to keep track of
updation and deletion of records.
Roll No.:
Class: TE (E&TC)
Division:
Signature:
Experiment No. -9
Title: Write a PL/SQL block to create trigger on Library table to keep track of updation and deletion
of records.
Problem Statement: Database Trigger (All Types: Row level and Statement level triggers, Before
and After Triggers). Write a database trigger on Library table. The System should keep track of the
records that are being updated or deleted. The old value of updated or deleted records should be
added in Library_Audit table.
Objective: To learn the concept of PL/SQL.
Hardware requirements: Any CPU with Pentium Processor or similar, 256 MB RAM or more, 1
GB Hard Disk or more.
Software requirements: Windows Operating System, MySQL
Theory:
DATABASE TRIGGERS:-
A database trigger is a PL/SQL program unit, which gets fired automatically whenever the data
event such as DML or DDL system event. Triggers are associated with a specific table and are
fired automatically whenever the table gets manipulated in a predefined way. The act of executing
a trigger is called as firing a trigger. Triggers are similar to procedures in that they are named
PL/SQL blocks with declarative, executable and exception handling sections. But the difference is
a procedure is executed explicitly from another block via a procedure call but a trigger is executed
implicitly whenever the triggering event happens. A procedure can pass arguments but trigger
doesn‟t accept arguments
1)Trigger type
2)Triggering time
3)Triggering event
Trigger types
1.Statement Trigger:-A statement trigger is a trigger in which the trigger action is executed once
for the manipulation operation that fires the trigger.
2.Row Trigger:-A row trigger is a trigger in which the trigger action is performed repeatedly for
each row of the table that is affected by the manipulation operation that fires the trigger.
Triggering time
1) Before the triggering event : The trigger action is performed before the operation that fires
the trigger is executed. This trigger is used when execution of operation depends on trigger
action.
2) After the triggering event : The trigger action is performed after the operation that fires the
trigger is executed. This trigger is used when triggering action depends on the execution of
operation. Triggering Events
Triggering events are the DML operations. These operations are insert, update and delete When
these operations are performed on a table, the trigger which is associated with the operation is
fired. Triggering events divide triggers into three types.
1) DELETE TRIGGER
2) UPDATE TRIGGER
3) INSERT TRIGGER
<BEFORE | AFTER>
ON <table_name>
……… ………
………………. End;
Where
Trigger_name:-trigger name is the name of the trigger. Table_name :-is thye table name for which
the trigger is defined.
Trigger-condition:-The trigger condition in the when clause,if present is evaluated first.The body
of the trigger is executed only when this condition evaluates to true.
Dropping trigger
The Trigger can be disabled without dropping them. When the trigger is disabled, it is still exists in
data dictionary but never fired, To disable trigger, use alter command.
Syntax:-
Syntax:-
Conclusion:
Experiment No: 10
Roll No.:
Class: TE (E&TC)
Division:
Signature:
Installation Steps:
In Eclipse perform following steps:
1. File - New – Java Project –Give Project Name – ok
2. In project Explorer window- right click on project name-newclass- give Class name- ok
3. In project Explorer window- right click on project name- Build
path- Configure build path- Libraries- Add External Jar - JavaMySQL Connector
4. In MySQL first Create one Database with name db1 and one
table with name stud(name,age)
Import packages, Load Driver, Create connection with MySQL Database
1) Import packages : import java.sql.*;
2) Load Driver: Class.forName("oracle.jdbc.driver.OracleDriver");
3) Create connection Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/DatabaseName","username","passwd ");
Create JDBC statement(s)
1) executeUpdate – This Method is used for insert, update and delete queries
• Example • String sql = “INSERT INTO stud VALUES (‘Ankita’,21)";
2) stmt.executeUpdate(sql);
3) String sql = “update stud set name=‘sumit’ where name=‘Ankita’; • stmt.executeUpdate(sql);
4) Example • String sql = “delete from stud where name=‘sumit’ "; • stmt.executeUpdate(sql);
//executeQuery used to run the select query and store the result in ResultSet while (rs.next())
//Store name data into name1 variable int age1 = rs.getInt(“age"); //Store age data into age1 variable }
Close connection
stmt.close();
con.close();
Sample program
import java.sql.*;
try{
Class.forName("com.mysql.jdbc.Driver");
Connection c =
DriverManager.getConnection("jdbc:mysql://
Statement sm = c.createStatement();
int ch;
do {
ch=s.nextInt();
switch (ch) {
sm.executeUpdate(sql);
System.out.println(“Record is Inserted");
break;
ResultSet rs = sm.executeQuery(sql);
while(rs.next())
break;
sm.executeUpdate(sql);
System.out.println(“Record is updated");
break;
sm.executeUpdate(sql);
System.out.println(“Record is deleted");
break;
} }while(ch<5);
catch(Exception e){
e.printStackTrace();
}}}
Conclusion: