Final DBMS Lab
Final DBMS Lab
Final DBMS Lab
PL/SQL Architecture
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 90’s to enhance the capabilities
of SQL. Execution of PL/SQL Block:
The PL/SQL statements written on the client side are passed to the PL/SQL engine
at server side and all the SQL statements are send to the SQL executer.
After the execution of whole block the result is send back to the client side.
The execution of the whole block is done in one go.
29
Difference Between SQL & PL/SQL
Assignments
The assignment statement sets the current value of a variable, field, parameter, or element that
has been declared in the current scope. The assignment operator (:=) in the assignment
statement can also appear in a constant or variable declaration. In a variable declaration, it
assigns a default value to the variable. Without a default value, a variable is initialized to
NULL every time a block is entered. If a variable does not have a default value, always use the
assignment statement to assign a value to it before using it in an expression.
30
Expression
An expression is an arbitrarily complex combination of operands (variables, constants, literals,
operators, function calls, and placeholders) and operators. The simplest expression is a single
variable. The PL/SQL compiler determines the data type of an expression from the types of the
operands and operators that comprise the expression. Every time the expression is evaluated, a
single value of that type results.
Syntax expression ::=
Program:
31
dbms_output.put_line('Product is: ' ||r3);
dbms_output.put_line('Division is: ' ||r4);
end;
Referencing Non SQL parameters
Variable g_monthly_salary number
Define p_manual_salary=60000
Declare
y_salary number(9,2)=&p_annual_salary
Begin
g_monthly_salary=y_salary/12;
End;
Print g_monthly_salary
Outcome:
By this process the students learns about the PL/SQL Architecture, Assignments and Expressions,
Writing PL/SQL Code, Referencing Non-SQL parameters.
32
Experiment 7: Stored Procedures and Exception Handling.
Objective: Students will be able to gain knowledge of Stored procedures and
how to handle exception.
Description:
Procedures: Procedures are named PL/SQL blocks that can take parameters, perform an
action and can be invoked. A procedure is generally used to perform an action and to pass
values. Procedures are made up of:
1. A declarative part
2. An executable part
3. An optional exception handling part
Declarative Part: The declarative part may contain declaration of cursors, constants,
variables, exceptions and subprograms. These objects are local to the procedure. The
objects become invalid once you exit from it.
Executable Part: This part contains PL/SQL block consisting of statements that assign
values, control execution and manipulate ORACLE data.
Exception Handling Part: This part contains code that performs action to deal with
exceptions raised during the execution of the program.
Syntax
CREATE OR REPLACE
PROCEDURE [schema] procedure_name (argument {IN, OUT, IN OUT}
datatype){IS, AS} Variable declarations;
Constant declarations; BEGIN
PL/SQL subprogram body; EXCEPTION
Exception PL/SQL
block; END;
Types of Procedures:
1. Local Procedure
2. Stored Procedure
Local Procedure: These procedures are declared within the PL/SQL block and called
from the begin section of the PL/SQL block.
33
The following is a simple example of a procedure:
Program:
declare
a number; b number; c number; d number; e number; f number;
procedure process ( a in number, b in number, c out number, d out number, e out
number, f out number) is
|| f);
end;
OUTPUT
Syntax:
34
WHEN exception THEN statement;
Program:
Outcome:
By this process the students learns about the Stored procedures and how to handle exception.
35
Experiment 8: Triggers and Cursor Management in PL/SQL
Objective: Students will be able to gain knowledge of how to manage triggers and
cursors in PL/SQL.
Description:
Triggers: A trigger is a special kind of stored procedure that is invoked whenever an attempt
is made to modify the data in the table it protects. Triggers are automatically executed or
fired when some events occur. Modifications to the table are made using INSERT,
UPDATE, ORDELETE statements. Triggers are used to enforce data integrity and business
rules such as automatically updating summary data. It allows performing cascading delete
or updating operations. If constraints exist on the trigger table, they are checked prior to
the trigger execution. If constraints are violated statement will not be executed and trigger
will not run. Triggers are associated with tables and they are automatic. Triggers are
automatically invoked by SQL SERVER. Triggers prevent incorrect, unauthorized, or
inconsistent changes to data.
Uses of Triggers:
1. A trigger can permit DML statements against a table only if they are issued, during
regular business hours or on predetermined weekdays.
2. A trigger can also be used to keep an audit trail of a table.
3. It can be used to prevent invalid transactions.
4. Enforce complex security authorizations.
5. Exception handling.
6. Generation of primary key and foreign key.
How to apply Triggers:
A trigger has three basic parts:
1. Triggering Event or Statement: It is a SQL statement that causes a trigger to be fired.
It can be an INSERT, UPDATE or DELETE statement for a specific table.
2. Trigger Restriction: A trigger restriction specifies a Boolean expression that must
be TRUE for the trigger to fire. It is an option available for triggers that are fired
for each row. A trigger restriction is specified using a WHEN clause.
3. Trigger Action: A trigger action is the PL/SQL code to be executed when a
triggering statement is encountered and any trigger restriction evaluates to TRUE.
36
Types of Triggers
• Row Triggers: A row trigger is fired each time the table is affected by the triggering
statement, for example, if an UPDATE statement update multiple rows of a table, a row
trigger is fired once for each row affected by the UPDATE statement.
• Statement Triggers: A row trigger is fired once on behalf of the triggering statement,
independent of the number of rows the triggering statement affects.
• Before Triggers: Before triggers execute the trigger action before the triggering
statement. These types of triggers are commonly used in the following situations:
1. BEFORE triggers are used when the trigger action should determine whether or
not the triggering statement should be allowed to complete. By using BEFORE
trigger, user can eliminate unnecessary processing of the triggering statement.
2. BEFORE triggers are used to derive specific column values before completing a
triggering INSERT or UPDATE statement.
• After Triggers: After triggers execute the trigger after the triggering statement is
executed. These types of triggers are commonly used in the following situations:
1. AFTER triggers are used when the triggering statement should complete before
executing the trigger action.
2. If a BEFORE trigger is already present, an AFTER trigger can perform different
actions on the same triggering statement.
Combinations Triggers: Using the above triggers, four types of triggers could be created.
There are twelve combinations of triggers.
Before Statement Trigger: Before executing the triggering statement, the trigger action is
executed.
Before Row Trigger: Before modifying each row affected by the triggering statement and
BEFORE applying appropriate integrity constraints, the trigger is executed.
After Statement Trigger: After executing the triggering statement and applying and
deferred integrity constraints, the trigger action is executed.
After Row Trigger: After modifying each row affected by the triggering statement and
applying appropriate integrity constraints, the trigger action is executed for the current row.
Unlike BEFORE row triggers, AFTER row triggers have rows locked.
37
Creation of Triggers: Triggers are created with the CREATE TRIGGER statement. This
statement specifies that the on which table trigger is defined and on which events trigger will
be invoked.
Syntax:
Deleting a Trigger: To drop Trigger one can use DROP TRIGGER statement.
Syntax:
Example
To start with, using the CUSTOMERS table Select * from customers;
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+ + + + + +
38
The following program creates a row-level trigger for the customers table that would fire
This trigger will display the salary difference between the old values and new values −
When the above code is executed at the SQL prompt, it produces the following result −
Trigger created.
Triggering a Trigger:
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (7, ',Kriti', 22, 'HP', 7500.00 ); When a record is
created in the CUSTOMERS table, the above create trigger, display_salary_changes will
be fired and it will display the following result – Old salary:
39
New salary: 7500 Salary difference:
Because this is a new record, old salary is not available and the above result comes as
null.
WHERE id = 2;
When a record is updated in the CUSTOMERS table, the above create trigger,
CURSORS:
Oracle DBA uses a work area for its internal processing. This work area is private to SQL’s
operations and is called Cursor. The data that is stored in the cursor is called the Active Data
Set. The size of the cursor in memory is the size required to hold the number of rows in the
active data set.
A PL/SQL block of code includes the Procedural code for looping and branching along
with the SQL statement. If records from a record set created using a select statement are to
be evaluated and processed one at a time, then the only method available is by using Explicit
Cursors.
TYPES OF CURSORS:
Implicitcursors.
Explicitcursors.
40
ATTRIBUTES OF CURSORS: Oracle provides certain attributes/cursor variables to
control the exception of a cursor. Whenever any cursor is opened and used, Oracle creates a
set of four system variables via which Oracle keeps track of the ‘Current’ status of the
cursor. We can access these variables. The implicit and explicit cursors have four attributes
as described below:
3. %ISOPEN: Oracle automatically closes the SQL cursor after executing its associated
SQL statement. As a result, sql%isopenalways evaluates to FALSE. If the explicit cursor
is open then it returns true otherwise false.
Syntax:
cursor_name%ISOPEN;
Syntax:
cursor_name%ROWCOUNT;
IMPLICIT CURSORS:
Oracle implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor. PL/SQL lets us refer to the most recent implicit cursor as the SQL
cursor. So, although we cannot use the open, fetch, and closestatements to control an implicit
cursor, we can still use cursor attributes to access information about the most recently
executed SQL statement.
41
Use cursor to select the five highest paid employees from the emp table showing tables
also.
Input Table:
Declare
cursor c1 isselectename, empno, sal from emp order by saldesc; -- start with highest paid
employee my_enamevarchar2(10);
my_empno number(4);
my_sal number(7,2);
Begin open c1;
fori in 1..5 loop
fetch c1 into my_ename, my_empno, my_sal; exit when c1%notfound;
insert into temp values (my_sal, my_empno, my_ename);
commit;
end loop;
close c1;
end;
Output Table:
Outcome:
By this process the students learns about the Triggers and Cursor Management in PL/SQL.
42
Experiment 9: Study of Web Databases.
Objective: Students will be able to gain knowledge of web databases.
Description:
Web Database: A web database is a wide term for managing data online. A web database
gives you the ability to build your own databases/data storage without you being a database
guru or even a technical person.
Examples: banks, airline and rental car reservations, university course registration and so on
The Web is a distributed information system base on hypertext.
Most Web documents are hypertext documents formatted via HTML
HTML Documents contain
Text along with font specifications, and other formatting instructions
Hypertext links to other documents , which can be associated with region of the text.
Data Organization
Web databases enable collected data to be organized and cataloged thoroughly within hundreds
of parameters. The Web database does not require advanced computer skills, and many
database software programs provide an easy “click-and-create” style with no complicated
coding. Fill in the fields and save each record. Organize the data however you choose, such as
chronologically, alphabetically or by a specific set of parameters.
Applicable Uses
Businesses both large and small can use Web databases to create website polls, feedback forms,
client or customer and inventory lists. Personal Web database use can range from storing
personal email accounts to a home inventory to personal website analytics. The Web database
is entirely customizable to an individual’s or business’s needs.
43
MySQL
Often in the world of Web databases, MySQL (structured query language) will be mentioned.
This is a relational database management system that manages different Web databases. It
operates as a server, and is an open source project. MySQL is often included with Web hosting
With a web server such as Apache (we assume Apache in this book, although the software
discussed here works with other web servers as well) and MySQL, you have most of what you
need to develop a web database application. The key glue you need is a way for the web server
to talk to the database; in other words, a way to incorporate database operations into web pages.
The most popular glue that accomplishes this task is PHP. PHP is an open-source project of the
Apache Software Foundation and it’s the most popular Apache web server add-on module, with
around 53% of the Apache HTTP servers having PHP capabilities. PHP is particularly suited
to web database applications because of its integration tools for the Web and database
environments. In particular, the flexibility of embedding scripts in HTML pages permits easy
integration of HTML presentation and code. The database tier integration support is also
excellent, with more than 15 libraries available to interact with almost all popular database
servers.
Apache, MySQL, and PHP can run on a wide variety of operating systems. In this book, we
show you how to use them on Linux, Mac OS X, and Microsoft Windows.
This is an introductory book, but it gives you the sophisticated knowledge you need to build
applications properly. This includes critical tasks such as checking user input, handling errors
robustly, and locking your database operations to avoid data corruption. Most importantly, we
explain the principles behind good web database applications. You’ll finish the book with not
44
only the technical skills to create an application, but also an appreciation for the strategies that
make an application secure, reliable, maintainable, and expandable.
The Web
When you browse the Web, you use your web browser to request resources from a web server
and the web server responds with the resources. You make these requests by filling in and
submitting forms, clicking on links, or typing URLs into your browser. Often, resources are
static HTML pages that are displayed in the browser. This is the classic two-tier or client- server
architecture used on the Web.
A two-tier architecture where a web browser makes a request and the web server responds
A web server is not sophisticated storage software. Complicated operations on data, done by
commercial sites and anyone else presenting lots of dynamic data, should be handled by a
separate database. This leads to a more complex architecture with three-tiers: the browser is
still the client tier, the web server becomes the middle tier, and the database is the third or
database tier. A web browser requests a resource that’s generated from a database, and how the
database and web server respond to the request.
45
Three-Tier Architectures
This book shows you how to develop web database applications that are built around the three-
tier architecture model. At the base of an application is the database tier, consisting of the
database management system that manages the data users create, delete, modify, and query.
Built on top of the database tier is the middle tier, which contains most of the application logic
that you develop. It also communicates data between the other tiers. On top is the client tier,
usually web browser software that interacts with the application.
For popular web sites, a common implementation is to install the web server and the database
server on different machines, so that resources are dedicated to permit a more scalable and
faster application. For very high-end applications, a cluster of computers can be used, where
the database and web servers are replicated and the load distributed across many machines. Our
focus is on simple implementations; replication and load distribution are beyond the scope of
this book.
Describing web database applications as three-tier architectures makes them sound formally
structured and organized. However, it hides the reality that the applications must bring together
different protocols and software, and that the software needs to be installed, configured, and
secured. The majority of the material in this book discusses the middle tier and the application
logic that allows web browsers to work with databases.
46
Features of Web database:
1. Save Money
One of the advantages of online database software is that it can save your business money.
When you don’t need to buy a software program for your business, this could result in a major
savings overall. In most cases, businesses pay for a software program and then pay for a
licensing fee for each computer that uses it. Using an online database may prove cheaper,
depending on the number of computers you use. You also don’t need to invest in servers to
store the data at your business.
2. Flexible Use
Another benefit of using an online database program is that it allows your business to be
flexible. You only pay for the amount of storage that you use. You need not worry about
purchasing servers as you go or eliminating them when they are no longer needed. If your
business grows or shrinks, you do not need to be concerned about the costs of database
management software or servers.
3. Technical Support
Another advantage of using a Web-based database program is that you can shift the technical
support burden to someone else. Paying a company for access to an online database includes
technical support. If the database has problems, you simply contact the the company and the
staff handles it. You don’t need to pay for an information technology professional for this
purpose. If you already have an IT department, your employees can focus on other things.
4. Access
Having access to the database at all times from multiple locations is another major advantage
of this type of database. With an online database, you could theoretically access the information
in the database from any computer. The information is also available 24 hours a day, seven
days a week. This means that all employees have access to the same information and can
collaborate with one another on projects — regardless of location. This advantage can increase
productivity and improve efficiency.
47
It’s based on a file management system (no actual database)
It is a table with several million entries, each entry being a keyword and a related
keyword, plus metrics that measure the quality of the match (how strong the
relationship between the two keywords is), as well as frequencies attached to these
two keywords, and when they are jointly found. The function to measure the quality
of the match can be customized by the user.
Outcome:
48
Experiment 10: Installation of Database Server.
Objective: Students will be able to gain knowledge of how to install database
server.
Description:
This explain the step by step installation process of MySQL database server. MySQL is open-
source, cross-platform relational database management server developed by Swedish company
“MySQL AB” and later acquired by Oracle corporation. MySQL is offered as an open-source
MySQL community server edition and enterprise server edition. Hence we will install the
MySQL Community server edition.
1. Developer default: If you want to create a development machine, you can use this
option. It installs the components which are required for application development, e.g.,
MySQL Server, MySQL Shell, MySQL connectors, MySQL
2. Server Only: If you want to create a standalone database server with specific
components, you can use this option
3. Full: If you want to install MySQL Server with its all components, then you can use
this option
4. Custom: If your requirements are limited to the few components, you can use this
option
We are going to install MySQL Server with all components; hence, choose “Full” and click
on Next.
49
Before installation begins, the installer checks all the prerequisites that are required to install
all the components of the MySQL database server. If any software prerequisites are missing,
then you can see the details of failing requirements on the “Check Requirements” screen. It
shows the name of the product, required component/software, and its status. As you can see, to
install the MySQL database server for visual studio, we must install visual studio 2015 or
above. Similarly, to install Python connector, we must install python on the work station. Click
on Next.
50
An installer gives us a warning. We can continue our installation without installing the visual
studio and python. Click on Yes.
On the Installation screen, you can see the list of the MySQL products/software that are going
to be installed on my workstation. Review the list and click on Execute.
51
The installer downloads all the products/software. After that, it installs all the products. Wait
for a few mins. Once the installation process completes, we are ready to configure the MySQL
database server and other components. Click on Next.
On the Product configuration screen, you can see the list of the products that need to be
configured. First, let us configure the MySQL Server. Click on Next.
On the High availability screen, we can choose to install the InnoDB cluster or Standalone
MySQL Server. InnoDB cluster is the High availability solution of MySQL. It uses group
replication. I will explain more about it in my future series of articles. We are going to perform
a standalone installation of MySQL Server hence choose “Standalone MySQL Server /
Classic MySQL Replication”.
On Type and Networking screen, we can configure the following:
The type of MySQL configuration.
The type of MySQL configuration is a predefined set of configuration parameter that
determines how much resources should be allocated to the MySQL Services. You have three
configuration options:
52
3. Dedicated Computer: This option is used when we have created a dedicated MySQL
Server. The configuration allocates a high amount of resources to MySQL Service
We would configure the server with minimal resources hence select “Development computer”
from the Config Type drop-down box.
Network Connectivity
In this section, we can control how clients can connect to MySQL databases. We can use
TCP/IP protocol or Named Pipe or Shared Memory. If you want to configure Named Pipe /
Shared Memory, we must provide the Pipe Name and Memory Name. You can also specify the
default port to connect to the database server. You can also choose to allow the port number
specified in Port textbox in the firewall. See the following image:
53
In MySQL 8.0 version, we can use SHA256 based strong passwords. On the Authentication
Method screen, choose the option to use the Legacy authentication method or Strong password
for authentication. Note: If you are using Strong Password Encryption for Authentication, then
make sure that all the connectors must be updated to the latest version. We are going to use
Strong password Encryption for Authentication.
On Accounts and Roles screen, you can specify the MySQL root account password. MySQL
Root account is a default sysadmin account, and it must be disabled.
You can also create other users to do that click on Add user. On MySQL User account dialog
box, provide a username, hostname, Role of the User, type of authentication, and password.
Once the user is created, click on Next. See the following image:
On the Windows Service screen, you can configure the MySQL server to run as a windows
service. You can provide the desired name and configure it to auto-start the service when the
system reboots. Moreover, you can provide the credentials under which the MySQL Service
54
will run. You can choose the standard system account or provide a specific user. See the
following image:
On the Apply Configuration screen, you can see the list of confirmation steps. Once all the
configuration settings are verified, click on Execute.
The MySQL installation process starts. You can view the installation process in the “Log” tab.
Once installation completes successfully, click on “Finish” to close the installer.
On the Apply Configuration Screen, click on Execute to start the installation of the Sample
database. See the following:
Once the sample database has been installed, click on the Finish button.
The installer continues to the Product Configuration screen. On this screen, you can see that
the installation of the MySQL Server 8.0.19 and Sample and Example 8.0.19 has been
completed successfully. See the following image:
56
Once the installation completes, you can copy the installation logs on the clipboard to review
it later. Moreover, if you want to start exploring MySQL straight away, then you can select
“Start MySQL workbench after Setup” and “Start MySQL Shell after Setup” and click on
Finish. See the following image:
57
On MySQL workbench welcome screen, you can see the list of MySQL connections. We have
not configured multiple connections; hence you can see “Local instance MySQL80.” Click
on it to open the new query editor window.
When you click on the connection, you must enter the credentials to connect the database
server. Enter the password and click on OK.
First, let’s create a simple database on MySQL Server. Write the following query in the query
editor window and click on execute. See the following image:
58
Once the query executes successfully, you can see the new database in the “SCHEMAS” pan.
See the following image
Outcome:
By this process the students learns about the installation of database server.
59