PL/SQL
What is PL/SQL
Procedural Language – SQL
An extension to SQL with design features of
programming languages (procedural and
object oriented)
PL/SQL and Java are both supported as
internal host languages within Oracle
products.
Why PL/SQL
Acts as host language for stored
procedures and triggers.
Provides the ability to add middle tier
business logic to client/server
applications.
Provides Portability of code from one
environment to another
Improves performance of multi-query
transactions.
Provides error handling
PL/SQL BLOCK STRUCTURE
DECLARE (optional)
- variable declarations
BEGIN (required)
- SQL statements
- PL/SQL statements or sub-blocks
EXCEPTION (optional)
- actions to perform when errors occur
END; (required)
PL/SQL Block Types
Anonymou Procedure Function
s
PROCEDURE <name> FUNCTION <name>
DECLARE IS RETURN <datatype>
BEGIN BEGIN IS
-statements -statements BEGIN
EXCEPTION EXCEPTION -statements
END; END; EXCEPTION
END;
PL/SQL Variable Types
Scalar (char, varchar2, number, date, etc)
Composite (%rowtype)
Reference (pointers)
LOB (large objects)
Variable Naming
Conventions
Two variables can have the same name if
they are in different blocks (bad idea)
The variable name should not be the same
as any table column names used in the
block.
PL/SQL is strongly typed
All variables must be declared before their
use.
The assignment statement
:=
is not the same as the equality operator
=
All statements end with a ;
PL/SQL Sample Program
DECLARE
v_inv_value number(10,2);
v_price number(8,2) := 10.25;
v_quantity number(8,0) := 400;
BEGIN
v_inv_value := v_price * v_quantity;
dbms_output.put('The value is: ');
dbms_output.put_line(v_inv_value);
END;
PL/SQL Comments
DECLARE
v_salary number(9,2) := 40000;
BEGIN
/* this is a multi-line comment that
will be ignored by the pl/sql
interpreter */
v_salary := v_salary * 2;
END; -- end of program
PL/SQL Sample Program
(For Loop)
DECLARE
x NUMBER := 100;
BEGIN
FOR i IN 1..10 LOOP
IF MOD(i,2) = 0 THEN -- i is even
INSERT INTO temp VALUES (i, x, 'i is even');
ELSE
INSERT INTO temp VALUES (i, x, 'i is odd');
END IF;
x := x + 100;
END LOOP;
COMMIT;
END;
Example
Consider Students table with columns
(sid, fname, lname, major, gpa)
Example
DECLARE
v_max_gpa number(3,2);
v_numstudents number(4);
v_lname students.lname%type; Display the highest GPA
v_major students.major%type;
BEGIN
select max(gpa) into v_max_gpa
from students;
DBMS_OUTPUT.PUT_LINE ('The highest GPA is '||v_max_gpa);
select count(sid) into v_numstudents Retrieve the no. of students with highest GPA
from students
where gpa = v_max_gpa;
IF v_numstudents > 1 then
If no. of students
DBMS_OUTPUT.PUT_LINE ('There are '||v_numstudents||' withare moreGPA');
that than 1, then
ELSE display the count or else display the
select lname, major into v_lname, v_major lname and major of the hisghest GPA
from students scorer.
where gpa=v_max_gpa;
DBMS_OUTPUT.PUT_LINE ('The student name is '||v_lname);
DBMS_OUTPUT.PUT_LINE ('The student major is '||v_major);
END IF;
END;
/
%ROWTYPE
Set serveroutput on
DECLARE
v_student students%rowtype;
BEGIN
select * into v_student
from students
where sid='123456';
DBMS_OUTPUT.PUT_LINE (v_student.lname);
DBMS_OUTPUT.PUT_LINE (v_student.major);
DBMS_OUTPUT.PUT_LINE (v_student.gpa);
END;
/
Stored Procedures
PL/SQL code stored in the database and executed when called by the
user.
Called by procedure name from another PL/SQL block or using
EXECUTE from SQL+. For example EXEC SQR(50)
Example:
Create procedure SQR (v_num_to_square IN number)
AS
v_answer number(10);
BEGIN
v_answer := v_num_to_square * v_num_to_square;
dbms_output.put_line(v_answer);
END;
BEGIN
SQR(19);
END;
Function
PL/SQL user defined function stored in the database and
executed when a function call is made in code: example x :=
SQUARED(50)
Example:
Create or Replace Function SQUARED
(p_number_to_square IN number)
RETURN number
IS
v_answer number(10);
BEGIN
v_answer := p_number_to_square * p_number_to_square;
RETURN(v_answer);
END;
select SQUARED(15) from dual
Cursors
A cursor is a temporary work area created in
the system memory when a SQL statement is
executed.
A cursor contains information on a select
statement and the rows of data accessed by it.
This temporary work area is used to store the
data retrieved from the database, and
manipulate this data.
A cursor can hold more than one row, but can
process only one row at a time. The set of
rows the cursor holds is called the active set.
CURSORS
A cursor is a private set of records
An Oracle Cursor = VB recordset = JDBC
ResultSet
Implicit cursors are created for every query
made in Oracle
Explicit cursors can be declared by a
programmer within PL/SQL.
Cursor Attributes
cursorname%ROWCOUNT Rows returned so far
cursorname%FOUND One or more rows
retrieved
cursorname%NOTFOUND No rows found
Cursorname%ISOPEN Is the cursor open
Explicit Cursor Control
Declare the cursor
Open the cursor
Fetch a row
Test for end of cursor
Close the cursor
Note: there is a FOR LOOP available with an implicit fetch
Sample Cursor Program
DECLARE
CURSOR students_cursor IS
SELECT * from students;
v_student students_cursor%rowtype;
/* instead we could do v_student students%rowtype */
BEGIN
DBMS_OUTPUT.PUT_LINE ('******************');
OPEN students_cursor;
FETCH students_cursor into v_student;
WHILE students_cursor%found LOOP
DBMS_OUTPUT.PUT_LINE (v_student.last);
DBMS_OUTPUT.PUT_LINE (v_student.major);
DBMS_OUTPUT.PUT_LINE ('******************');
FETCH students_cursor into v_student;
END LOOP;
CLOSE students_cursor;
END;
Sample Cursor Program
(same program without composite variable)
DECLARE
CURSOR students_cursor IS
SELECT last, major from students;
v_Last students.last%type;
v_major students.major%type;
BEGIN
DBMS_OUTPUT.PUT_LINE ('******************');
OPEN students_cursor;
FETCH students_cursor into v_last, v_major;
WHILE students_cursor%found LOOP
DBMS_OUTPUT.PUT_LINE (v_last);
DBMS_OUTPUT.PUT_LINE (v_major);
DBMS_OUTPUT.PUT_LINE ('******************');
FETCH students_cursor into v_last, v_major;
END LOOP;
CLOSE students_cursor;
END;
/
Stored Procedure Example
Write a procedure using cursor to display all
tablenames from user tables of Oracle database
Stored Procedure Example
Write a procedure using cursor to display all
tablenames from user tables of Oracle database
Create or replace procedure mytabs
AS
CURSOR table_cursor IS
Select table_name from user_tables;
v_tablename varchar2(30);
BEGIN
open table_cursor;
fetch table_cursor into v_tablename;
while table_cursor%found loop
dbms_output.put_line(v_tablename);
fetch table_cursor into v_tablename;
end loop;
close table_cursor;
END;
When is PL/SQL handy
When something is too complicated for SQL
When conditional branching and looping are
needed
JDBC
JDBC is a standard interface for connecting to
relational databases from Java.
The JDBC classes and interfaces are in the
java.sql package.
JDBC 1.22 is part of JDK 1.1; JDBC 2.0 is part
of Java 2
Overview of Querying a
Database With JDBC
Connect
Query
Process
results
Close
Stage 1: Connect
Connect Register the driver
Query Connect to the database
Process
results
Close
A JDBC Driver
Is an interpreter that translates JDBC method
calls to vendor-specific database commands
Database
JDBC calls commands
Driver
Database
Implements interfaces in java.sql
Can also provide a vendor’s extensions to the
JDBC standard
Oracle JDBC Drivers
Thin driver
◦ a 100% Java driver for client-side use
with an Oracle installation, particularly
with applets
OCI drivers (OCI8 and OCI7)
◦ for client-side use with an Oracle client
installation
Oracle JDBC Drivers: Thin Client Driver
Written entirely in Java
Applets must use this driver
Applet
JDBC
Thin driver Oracle
Client Server
Oracle JDBC Drivers: OCI Client
Drivers
Written in C and Java
Must be installed on the client
Application
JDBC
OCI driver
Oracle
ocixxx.dll
Client Server
Other JDBC Drivers
JDBC-ODBC Bridge
◦ Translates JDBC into open database connectivity
(ODBC) calls
◦ Allows communication with existing ODBC
drivers when no JDBC driver is available
JDBC URLs
JDBC uses a URL to identify the database
connection.
jdbc:<subprotocol>:<subname>
Database
Protocol Subprotocol
identifier
jdbc:oracle:<driver>:@<database>
JDBC URLs with Oracle
Drivers
Thin driver
jdbc:oracle:thin:@<host>:<port>:<SID>
OCI driver
jdbc:oracle:oci8:@<TNSNAMES entry>
How to Make the
Connection
1. Register the driver.
DriverManager.registerDriver (new
oracle.jdbc.driver.OracleDriver());
2.
2. Connect
Connect to
to the
the database.
database.
Connection conn = DriverManager.getConnection
(URL, userid, password);
Connection conn = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:XE","scott
2","tiger");
Stage 2: Query
Connect
Query Create a statement
Process Query the database
results
Close
The Statement Object
A Statement object sends your SQL
statement to the database.
You need an active connection to create a
JDBC statement.
Statement has three methods to execute a
SQL statement:
◦ executeQuery() for QUERY statements
◦ executeUpdate() for INSERT, UPDATE, DELETE,
or DDL statements
◦ execute() for either type of statement
How to Query the
Database
1. Create an empty statement object.
Statement stmt = conn.createStatement();
2. Execute the statement.
ResultSet rset = stmt.executeQuery(statement);
int count = stmt.executeUpdate(statement);
boolean isquery = stmt.execute(statement);
Querying the Database:
Examples
Execute a select statement.
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery
("select RENTAL_ID, STATUS from
ACME_RENTALS");
• Execute a delete statement.
Statement stmt = conn.createStatement();
int rowcount = stmt.executeUpdate
("delete from ACME_RENTAL_ITEMS
where rental_id = 1011");
Stage 3: Process the
Results
Connect
Query
Step through the results
Process Assign results to Java
results variables
Close
The ResultSet Object
JDBC returns the results of a query in a
ResultSet object.
A ResultSet maintains a cursor pointing to
its current row of data.
Use next() to step through the result set row
by row.
getString(), getInt(), and so on assign each
value to a Java variable.
How to Process the Results
1. Step through the result set.
while (rset.next()) { … }
2. Use getXXX() to get each column
value.
String val =
rset.getString(colname);
while (rset.next()) {
String title = rset.getString("TITLE");
String year = rset.getString("YEAR");
… // Process or display the data
}
Stage 4: Close
Connect
Query
Close the result set
Process
results Close the statement
Close Close the connection
How to Close the
Connection
1. Close the ResultSet object.
rset.close();
2. Close the Statement object.
stmt.close();
3. Close the connection (not necessary for
server-side driver).
conn.close();