UNIT-3
PL/SQL
DATABASE
APPLICATION
DEVELOPMENT
Embedded SQL
❑In real time applications we need access to a database from a general-
purpose programming language.
For Example, to integrate a database application with a nice graphical user
interface, or we may want to ask a query that cannot be expressed in SQL.
SQL provides a powerful declarative query language- Embedded of SQL.
❑The use of SQL commands within a host language program like c ,java is
called Embedded SQL.
❑ The SQL standard defines embedding of SQL as embedded SQL and the
language in which SQL queries are embedded is referred as host
language.
Complications
► First, the data types recognized by SQL may not be
recognized by the host language and vice versa.
► This mismatch is typically addressed by casting data
values appropriately before passing them to or from
SQL commands.
► The second complication has to do with SQL being set-
oriented, and is addressed using cursors.
Declaring Variables and Exceptions
► SQL statements can refer to variables
defined in the host program.
► Host language variables must be prefixed by
a colon (:) in SQL statements and be
declared between the commands
EXEC SQL BEGIN DECLARE SECTION and EXEC
SQL END DECLARE SECTION.
EXEC SQL BEGIN DECLARE SECTION
char :c_sname[20];
long :csid;
short :crating;
float :cage;
EXEC SQL END DECLARE SECTION
SQLCODE and SQLSTATE
► To report what went wrong if an error condition
arises when executing an SQL statement.
► The SQL-92 standard recognizes two special
variables for reporting errors, SQLCODE and
SQLSTATE.
► SQLCODE is the older of the two and is defined to
return some negative value when an error
condition arises, without specifying further just
what error a particular negative integer denotes.
► SQLSTATE, introduced in the SQL-92 standard for
the first time, associates predefined values with
several common error conditions, thereby
introducing some uniformity to how errors are
reported.
► All SQL statements embedded within a host
program must be clearly marked, SQL
statements must be prefixed by EXEC SQL.
► Observe that a semicolon terminates the
command, as per the convention for
terminating statements in C.
► The SQLSTATE variable should be checked for errors and exceptions
after each Embedded SQL statement. SQL provides the WHENEVER
command to simplify this tedious task
► If SQLERROR is specified and the value of SQLSTATE indicates an
exception, control is transferred to stmt, which is presumably
responsible for error and exception handling.
PL/SQL
► When SQL statements are issued from a remote application, the
records in the result of the query need to be transferred from the
database system back to the application.
► Once a stored procedure is registered with the database server,
different users can re-use the stored procedure, eliminating
duplication of efforts in writing SQL queries or application logic,
and making code maintenance.
► In addition, application programmers do not need to know the
database schema if we encapsulate all database access into
stored procedures
PL/SQL
► PL/SQL is a procedural language extension to Structured Query Language
(SQL).
► The purpose of PL/SQL is to combine database language and procedural
programming language.
► The basic unit in PL/SQL is called a block and is made up of three parts: a
declarative part, an executable part and an exception-building part.
► A PL/SQL program that is stored in a database in compiled form and can
be called by name is referred to as a stored procedure
Differences between SQL and PL/SQL
SQL PL/SQL
SQL is a single query that is used PL/SQL is a block of codes that used
to perform DML and DDL to write the entire program blocks/
operations. procedure/ function, etc.
Execute as a single statement. Execute as a whole block.
Mainly used to manipulate data. Mainly used to create an application.
Cannot contain PL/SQL code in It is an extension of SQL, so it can
it. contain SQL inside it.
Structure of PL/SQL Block
► The basic unit in PL/SQL is a block. All
PL/SQL programs are made up of
blocks, which can be nested within each
other. PL/SQL contains 4 main blocks
► Declare
► Begin
► Exception DECLARE
Declaration statement;
► End BEGIN
Executable statements;
EXCEPTIONS
► Typically, each block performs a logical Exception handling statements;
action in the program. A block has the
following structure: END;
PL/SQL Identifiers
► There are several PL/SQL identifiers such as procedures, cursors, triggers
etc.
Variables:
► Like several other programming languages, variables in PL/SQL must be
declared prior to its use. They should have a valid name and data type as
well.
SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
var1 INTEGER;
var2 REAL;
var3 varchar2(20) ;
BEGIN
null;
END;
/
Output:
PL/SQL procedure successfully completed
INITIALISING VARIABLES
► Example for initializing variable
SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
var1 INTEGER := 2 ;
var3 varchar2(20) := ‘Hi Everyone!!!!';
BEGIN
null;
END;
/
Output:
PL/SQL procedure successfully completed
DISPLAYING OUTPUT
► The outputs are displayed by using DBMS_OUTPUT which is a built-in
package that enables the user to display output.
SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
var varchar2(40) := ‘Hi Everyone';
BEGIN
dbms_output.put_line(var);
END;
/
Output:
Hi Everyone
PL/SQL procedure successfully completed
TAKING INPUT FROM USER
► Just like in other programming languages, in PL/SQL also, we can take
input from the user and store it in a variable
SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
-- taking input forvariable a
a number := &a;
-- taking input forvariable b
b varchar(30) := &b;
BEGIN
null;
END;
/
Output:
PL/SQL procedure successfully completed
Example 1:
--PL/SQL code to print sum of two numbers taken from the user.
SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
-- taking input forvariable a
a integer := &a ;
-- taking input forvariable b
b integer := &b ;
c integer ;
BEGIN
c := a + b ;
dbms_output.put_line('Sum of '||a||' and '||b||' is = '||c);
END;
/
Output:
2
3
Sum of 2 and 3 is =5
PL/SQL procedure successfully completed
Example 2:
--PL/SQL code to print natural numbers from 1 to 5
SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
i number;
BEGIN
i:=1;
loop
dbms_output.put_line(i);
i:= i+1;
exit when i>5;
end loop;
END;
/
Procedure (stored procedure)
► A stored procedure is a prepared SQL code that you can save, so the code can
be reused over and over again.
► You can also pass parameters to a stored procedure. They are:
IN:
This is the Default Parameter for the procedure. It always receives the values
from calling program.
OUT:
This parameter always sends the values to the calling program.
IN OUT:
This parameter performs both the operations. It Receives value from as well as
sends the values to the calling program.
Syntax : Creating a Procedure
CREATE or REPLACE PROCEDURE name(parameters)
IS
variables;
BEGIN
//statements;
END;
CREATE PROCEDURE SQL> DECLARE
FINDMIN(X IN NUMBER,Y IN A NUMBER:=20;
NUMBER,Z OUT NUMBER) IS
B NUMBER:=10;
BEGIN
C NUMBER;
IF X<Y THEN
BEGIN
Z:=X;
FINDMIN(A,B,C);
ELSE
DBMS_OUTPUT.PUT_LINE('MIN OF A AND B
Z:=Y; IS'||C);
END IF; END;
END; /
/ MIN OF A AND B IS10
Procedure created. PL/SQL procedure successfully completed.
CURSORS
► It essentially provide a mechanism that allows us to retrieve rows
one at a time from a relation. This mechanism is called a cursor.
► Cursors are used when the user needs to update records in a
singleton fashion or in a row by row manner, in a database table.
► A cursor can be declare on any relation or on any SQL query
(because every query returns a set of rows).
► Once a cursor is declared,
1. Open it (which positions the cursor just before the first row);
2. Fetch the next row
3. move the cursor
4. Close the cursor
Employee11 table:
ODBC and JDBC
∙ Embedded SQL enables the integration of SQL with a general-purpose programming
language. A DBMS-specific pre-processor transforms the Embedded SQL statements
into function calls in the host language.
∙ ODBC and JDBC, short for Open Database Connectivity and Java Database
Connectivity, also enable the integration of SQL with a general-purpose programming
language.
∙ Both ODBC and JDBC expose database capabilities in a standardized way to the
application programmer through an application programming interface (API).
∙ Using ODBC or JDBC, an application can access not just one DBMS but several
different ones simultaneously.
∙ All direct interaction with a specific DBMS happens through a DBMS-specific
driver. A driver is a software program that translates the ODBC or JDBC calls
into DBMS-specific calls.
∙ Drivers are loaded dynamically on demand since the DBMSs the application is
going to access are known only at run-time.
∙ It is sufficient that the driver translates the SQL commands from the
application into equivalent commands that the DBMS understands.
∙ An application that interacts with a data source through ODBC or JDBC selects a
data source, dynamically loads the corresponding driver, and establishes a
connection with the data source.
∙ While a connection is open, transactions are executed by submitting SQL
statements, retrieving results, processing errors, and finally committing or
rolling back. The application disconnects from the data source to terminate the
interaction.
Architecture
► The architecture of JDBC has four main components: the application, the corresponding data
sources, the driver manager and several data source specific drivers,
i) The application initiates and terminates the connection with a data source. It submits SQL statements,
and retrieves the results-----all through a well-defined interface as specified by the JDBC API.
ii) The data source processes commands from the driver and returns the results. Depending on the
relative location of the data source and the application, several architectural scenarios are possible.
iii)The primary goal of the driver manager is to load JDBC drivers and pass JDBC function calls from
the application to the correct driver.
iv) The data source specific driver handles JDBC initialization and information calls from the
applications and can log all function calls. In addition, it performs· error checking & establishes the
connection with the data source. In addition to submitting requests and returning request results, the
driver translates data, error formats, and error codes from a form that is specific to the data source into
Definition of JDBC
► It is a standard interface between any Java application and different databases.
The function of JDBC is to help the Java-based application to access different
types of databases. JDBC provide methods to query database, and it can also be
used to update the database. JDBC provide JDBC drivers that converts the
request from Java application on client side to the language that database
understands.
► As JDBC is language and platform specific, Java application can use JDBC-to-
ODBC Bridge to communicate with ODBC adaptable databases. Unlike
ODBC, JDBC has easy coding but, it is only limited to Java only.
JDBC
► Java database connectivity. Its an API.
► It enable Java applications to use SQL for database access.
► Its acts like an interface between java program and database.
► It pass the value from frontend to backend.
Procedure :
Import the package , register the jdbc driver , open a connection ,
Execute a query , extract data from resultset, close connection.
Definition of ODBC
► ODBC is Open Database Connectivity. Like JDBC, ODBC is also an API
that acts as an interface between an application on the client side and the
database on the server side.
∙ ODBC helps an application to access the data from the database. An
application written in any language can use ODBC to access different types of
databases and hence, it is said to be language and platform independent.
∙ ODBC is most widely used and understands many different programming
languages. But its code is complex and hard to understand.
► Similarity: Both are used by the client-side applications to access different
kinds of databases on server side.
TRIGGERS
❑A trigger is a procedure that is automatically invoked by the
DBMS in response to specified changes to the database, and is
typically specified by the DBA.
❑A database that has a set of associated triggers is called an active
database.
❑A trigger description contains three parts:
✔Event: A change to the database that activates the trigger.
✔Condition: A query or test that is run when the trigger is
activated.
✔Action: A procedure that is executed when the trigger is
activated and its condition is true.
TRIGGERS
❑An insert, delete or update statement could activate a trigger,
regardless of which user or application invoked the activating
statement.
❑A condition in a trigger can be a true/false statement or a
query.
❑If the condition part evaluates to true, the action associated
with the trigger is executed.
TRIGGERS
❑In fact, an action can even execute a series of data-definition
commands (e.g., create new tables, change authorizations) and
transaction-oriented commands (e.g., commit), or call host
language procedures.
❑The execution of the action part of a trigger could again
activate the same trigger such triggers are called recursive
triggers.
TRIGGERS
Constraints versus Triggers
❑Triggers are active, while constraints are passive. While constraints prevent
updates that violate referential integrity, triggers perform explicit actions in addition
to the update operation.
❑Triggers can do much more than enforce referential integrity. Because they are
passive, constraints are limited to preventing updates in a narrow set of conditions.
❑A common use of triggers is to maintain database consistency.
❑The meaning of a constraint is not defined operationally, unlike the effect of a
trigger.
❑This property makes a constraint easier to understand, and also gives the DBMS
more opportunities to optimize execution.
TRIGGERS
Constraints versus Triggers
❑A constraint also prevents the data from being made inconsistent by
any kind of statement, whereas a trigger is activated by a specific kind
of statement (e.g., an insert or delete statement). Again, this restriction
makes a constraint easier to understand.
❑On the other hand, triggers allow us to maintain database integrity in
more flexible ways.
DESIGNING ACTIVE DATABASES
► Triggers offer a powerful mechanism for dealing
with changes to a database, but they must be
used with caution.
► The effect of a collection of triggers can be very
complex and maintaining an active database can
become very difficult.
► Often, a judicious use of integrity constraints can
replace the use of triggers.
Why Triggers Can Be Hard to
Understand
► In an active database system, when the DBMS is about to execute a
statement that modifies the database, it checks whether some trigger is
activated by the statement.
► If so, the DBMS processes the trigger by evaluating its condition part, and
then (if the condition evaluates to true) executing its action part.
► If a statement activates more than one trigger, the DBMS typically
processes all of them, in some arbitrary order. An important point is that
the execution of the action part of a trigger could in turn activate another
trigger.
► In particular, the execution of the action part of a trigger could again
activate the same trigger; such triggers are called recursive triggers. The
potential for such chain activations, and the unpredictable order in which
a DBMS processes activated triggers, can make it difficult to understand
the effect of a collection of triggers.
Other uses of Triggers
► A common use of triggers is to maintain database
consistency.
► A constraint also prevents the data from being made
inconsistent.
► Anyways, Triggers allow us to maintain database integrity in
more flexible ways.
► Triggers can alert users to unusual events (as reflected in
updates to the database).
For example, we may want to check whether a customer
placing an order has made enough purchases in the past
month to qualify for an additional discount; if so, the sales
clerk must be informed so that he can tell the customer, and
possibly generate additional sales!
THANK YOU
Example:
Delimiter $$
Create procedure pro_cursor(id int) 101
Begin
declare name varchar(20);
declare mark int;
declare curl cursor for select stu_name from
stu_table where stu_id = id;
Open curl;
Fetch curl into name, mark; Output:
Select name;
call pro_cursor(101);
Close curl;
End$$
TRIGGERS
Trigger Declaration Syntax
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
Triggers Example
BEFORE INSERT
Create table student(
delimiter $$
Studentid int primary key,
Create Trigger calculate BEFORE INSERT ON
Fname varchar(20), student
Lname varchar(20), for each row
Address varchar(30), Begin
City varchar(15), set new.Marks= new.Marks+100;
Marks int); end;
$$
Triggers Example
AFTER INSERT
create table final_marks(
delimiter $$
Per int);
Create Trigger total_marks AFTER INSERT ON
student
for each row
Begin
insert into final_marks values(new.Marks);
end;
$$
Output:
Insert into student values(1,’raj’,’k’,’an’,’blore’,78);
select * from final_marks;
Triggers Example: BEFORE UPDATE
create table student_marks( DELIMITER
Studentid int primary key, $$
Name varchar(20), CREATE TRIGGER `student_marks_upd`
Sub1 int, BEFORE UPDATE ON student_marks
Sub2 int, FOR EACH ROW
Sub3 int, BEGIN
Total int, SET new.Total = new.Sub1 + new.Sub2 +
new.Sub3 ;
Per_marks int);
SET new.Per_marks = new.Total/3;
end;
$$
Output:
Update student_marks set Sub1 = 54, Sub2 = 69, Sub3 = 89;
Select * from student_marks;
Trigger Example: AFTER UPDATE
Delimiter$$ stu_table
Create trigger stu_update stu_id stu_name
AFTER UPDATE ON stu_table
For each row
Begin
insert into stu_log values(user(), concat(‘update stu_log
student record’,(’,old.stu_id’ , ‘,old.stu_name’) to user description
( ‘, new.stu_id’, ‘,new.stu_name’)));
End;
$$