SlideShare a Scribd company logo
1 of 12
Download to read offline
8/19/2016
Vinaya Sawant 1
 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.
 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
DECLARE (optional)
- variable declarations
BEGIN (required)
- SQL statements
- PL/SQL statements or sub-blocks
EXCEPTION (optional)
- actions to perform when errors occur
END; (required)
8/19/2016
Vinaya Sawant 2
Anonymous
DECLARE
BEGIN
-statements
EXCEPTION
END;
Procedure
PROCEDURE <name>
IS
BEGIN
-statements
EXCEPTION
END;
Function
FUNCTION <name>
RETURN <datatype>
IS
BEGIN
-statements
EXCEPTION
END;
 Scalar (char, varchar2, number, date, etc)
 Composite (%rowtype)
 Reference (pointers)
 LOB (large objects)
 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.
 All variables must be declared before their
use.
 The assignment statement
: =
is not the same as the equality operator
=
 All statements end with a ;
8/19/2016
Vinaya Sawant 3
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;
Accept p_price Prompt 'Enter the Price: '
DECLARE
v_inv_value number(8,2);
v_price number(8,2);
v_quantity number(8,0) := 400;
BEGIN
v_price := &p_price;
v_inv_value := v_price * v_quantity;
dbms_output.put_line('******');
dbms_output.put_line('price * quantity=');
dbms_output.put_line(v_inv_value);
END;
Note: PL/SQL not designed for user interface programming
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; -- nice raise
END; -- end of program
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;
8/19/2016
Vinaya Sawant 4
 Consider Students table with columns
(sid, fname, lname, major, gpa)
DECLARE
v_max_gpa number(3,2);
v_numstudents number(4);
v_lname students.lname%type;
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
from students
where gpa = v_max_gpa;
IF v_numstudents > 1 then
DBMS_OUTPUT.PUT_LINE ('There are '||v_numstudents||' with that
GPA');
ELSE
select lname, major into v_lname, v_major
from students
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;
/
Display the highest GPA
Retrieve the no. of students with highest GPA
If no. of students are more than 1, then
display the count or else display the
lname and major of the hisghest GPA
scorer.
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;
/
 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;
8/19/2016
Vinaya Sawant 5
 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
 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.
 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.
 cursorname%ROWCOUNT Rows returned so far
 cursorname%FOUND One or more rows retrieved
 cursorname%NOTFOUND No rows found
 Cursorname%ISOPEN Is the cursor open
8/19/2016
Vinaya Sawant 6
 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
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;
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;
/
Write a procedure using cursor to display all
tablenames from user tables of Oracle database
8/19/2016
Vinaya Sawant 7
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 something is too complicated for SQL
 When conditional branching and looping are
needed
 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
Query
Close
Connect
Process
results
8/19/2016
Vinaya Sawant 8
Query
Close
Connect
Process
results
Register the driver
Connect to the database
 Is an interpreter that translates JDBC method calls
to vendor-specific database commands
 Implements interfaces in java.sql
 Can also provide a vendor’s extensions to the JDBC
standard
Driver
JDBC calls
Database
commands
Database
 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
Applet
JDBC
Client Server
Thin driver
 Written entirely in Java
 Applets must use this driver
8/19/2016
Vinaya Sawant 9
Client Server
Oracle
Application
JDBC
OCI driver
ocixxx.dll
 Written in C and Java
 Must be installed on the client
 JDBC-ODBC Bridge
◦ Translates JDBC into open database connectivity
(ODBC) calls
◦ Allows communication with existing ODBC drivers
when no JDBC driver is available
jdbc:<subprotocol>:<subname>
Protocol
Database
identifier
jdbc:oracle:<driver>:@<database>
Subprotocol
 JDBC uses a URL to identify the database
connection.
 Thin driver
 OCI driver
jdbc:oracle:thin:@<host>:<port>:<SID>
jdbc:oracle:oci8:@<TNSNAMES entry>
8/19/2016
Vinaya Sawant 10
DriverManager.registerDriver (new
oracle.jdbc.driver.OracleDriver());
Connection conn = DriverManager.getConnection
(URL, userid, password);
Connection conn = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:XE",
"scott2","tiger");
2. Connect to the database.
1. Register the driver.
Close
Connect
Query Create a statement
Process
results
Query the database
 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
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery(statement);
int count = stmt.executeUpdate(statement);
boolean isquery = stmt.execute(statement);
1. Create an empty statement object.
2. Execute the statement.
8/19/2016
Vinaya Sawant 11
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery
("select RENTAL_ID, STATUS from ACME_RENTALS");
Statement stmt = conn.createStatement();
int rowcount = stmt.executeUpdate
("delete from ACME_RENTAL_ITEMS
where rental_id = 1011");
 Execute a select statement.
• Execute a delete statement.
Close
Query
Step through the results
Process
results
Assign results to Java
variables
Connect
 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.
while (rset.next()) { … }
String val = rset.getString(colname);
while (rset.next()) {
String title = rset.getString("TITLE");
String year = rset.getString("YEAR");
… // Process or display the data
}
 1. Step through the result set.
 2. Use getXXX() to get each column value.
8/19/2016
Vinaya Sawant 12
Connect
Query
Process
results
Close
Close the result set
Close the statement
Close the connection
1. Close the ResultSet object.
2. Close the Statement object.
3. Close the connection (not necessary for
server-side driver).
rset.close();
stmt.close();
conn.close();

More Related Content

What's hot

JSP Standard Tag Library
JSP Standard Tag LibraryJSP Standard Tag Library
JSP Standard Tag LibraryIlio Catallo
 
Jdbc in servlets
Jdbc in servletsJdbc in servlets
Jdbc in servletsNuha Noor
 
NUS Hackers Club Mar 21 - Whats New in JavaSE 8?
NUS Hackers Club Mar 21 - Whats New in JavaSE 8?NUS Hackers Club Mar 21 - Whats New in JavaSE 8?
NUS Hackers Club Mar 21 - Whats New in JavaSE 8?Chuk-Munn Lee
 
MuleSoft DataWeave data transformation language
MuleSoft DataWeave data transformation languageMuleSoft DataWeave data transformation language
MuleSoft DataWeave data transformation languagefganora
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySqlkamal kotecha
 
Best Practices for Interoperable XML Databinding with JAXB
Best Practices for Interoperable XML Databinding with JAXBBest Practices for Interoperable XML Databinding with JAXB
Best Practices for Interoperable XML Databinding with JAXBMartin Grebac
 
JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database ConnectivityRanjan Kumar
 
JSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTLJSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTLseleciii44
 
Introduction to Loops in Java | For, While, Do While, Infinite Loops | Edureka
Introduction to Loops in Java | For, While, Do While, Infinite Loops | EdurekaIntroduction to Loops in Java | For, While, Do While, Infinite Loops | Edureka
Introduction to Loops in Java | For, While, Do While, Infinite Loops | EdurekaEdureka!
 
Coveney pig lecture
Coveney pig lectureCoveney pig lecture
Coveney pig lectureSeven Nguyen
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivitybackdoor
 

What's hot (19)

JSP Standard Tag Library
JSP Standard Tag LibraryJSP Standard Tag Library
JSP Standard Tag Library
 
Jdbc basic features
Jdbc basic featuresJdbc basic features
Jdbc basic features
 
Jstl Guide
Jstl GuideJstl Guide
Jstl Guide
 
Jdbc in servlets
Jdbc in servletsJdbc in servlets
Jdbc in servlets
 
Jdbc
JdbcJdbc
Jdbc
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
 
Sql server
Sql serverSql server
Sql server
 
NUS Hackers Club Mar 21 - Whats New in JavaSE 8?
NUS Hackers Club Mar 21 - Whats New in JavaSE 8?NUS Hackers Club Mar 21 - Whats New in JavaSE 8?
NUS Hackers Club Mar 21 - Whats New in JavaSE 8?
 
MuleSoft DataWeave data transformation language
MuleSoft DataWeave data transformation languageMuleSoft DataWeave data transformation language
MuleSoft DataWeave data transformation language
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySql
 
Best Practices for Interoperable XML Databinding with JAXB
Best Practices for Interoperable XML Databinding with JAXBBest Practices for Interoperable XML Databinding with JAXB
Best Practices for Interoperable XML Databinding with JAXB
 
embedded-static-&dynamic
embedded-static-&dynamicembedded-static-&dynamic
embedded-static-&dynamic
 
JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database Connectivity
 
JSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTLJSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTL
 
Jdbc
JdbcJdbc
Jdbc
 
Introduction to Loops in Java | For, While, Do While, Infinite Loops | Edureka
Introduction to Loops in Java | For, While, Do While, Infinite Loops | EdurekaIntroduction to Loops in Java | For, While, Do While, Infinite Loops | Edureka
Introduction to Loops in Java | For, While, Do While, Infinite Loops | Edureka
 
JDBC ppt
JDBC pptJDBC ppt
JDBC ppt
 
Coveney pig lecture
Coveney pig lectureCoveney pig lecture
Coveney pig lecture
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 

Similar to 4. plsql 1

PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts Bharat Kalia
 
Laurens Van Den Oever Xopus Presentation
Laurens Van Den Oever Xopus PresentationLaurens Van Den Oever Xopus Presentation
Laurens Van Den Oever Xopus PresentationAjax Experience 2009
 
Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)Maher Abdo
 
The Making of the Oracle R2DBC Driver and How to Take Your Code from Synchron...
The Making of the Oracle R2DBC Driver and How to Take Your Code from Synchron...The Making of the Oracle R2DBC Driver and How to Take Your Code from Synchron...
The Making of the Oracle R2DBC Driver and How to Take Your Code from Synchron...VMware Tanzu
 
Relational Database Management System
Relational Database Management SystemRelational Database Management System
Relational Database Management Systemsweetysweety8
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's CodeWildan Maulana
 
Vision_Academy_Ajava_final(sachin_sir9823037693)_22.pdf
Vision_Academy_Ajava_final(sachin_sir9823037693)_22.pdfVision_Academy_Ajava_final(sachin_sir9823037693)_22.pdf
Vision_Academy_Ajava_final(sachin_sir9823037693)_22.pdfVisionAcademyProfSac
 
Vision_Academy_Ajava_final(sachin_sir9823037693)_22 (1).pdf
Vision_Academy_Ajava_final(sachin_sir9823037693)_22 (1).pdfVision_Academy_Ajava_final(sachin_sir9823037693)_22 (1).pdf
Vision_Academy_Ajava_final(sachin_sir9823037693)_22 (1).pdfbhagyashri686896
 
Sparkling Water 5 28-14
Sparkling Water 5 28-14Sparkling Water 5 28-14
Sparkling Water 5 28-14Sri Ambati
 
Pre-Con Ed: Using Java to Access Your CA IDMS Databases and Applications
Pre-Con Ed: Using Java to Access Your CA IDMS Databases and ApplicationsPre-Con Ed: Using Java to Access Your CA IDMS Databases and Applications
Pre-Con Ed: Using Java to Access Your CA IDMS Databases and ApplicationsCA Technologies
 
3.java database connectivity
3.java database connectivity3.java database connectivity
3.java database connectivityweb360
 

Similar to 4. plsql 1 (20)

Plsql
PlsqlPlsql
Plsql
 
SQL- Introduction to PL/SQL
SQL- Introduction to  PL/SQLSQL- Introduction to  PL/SQL
SQL- Introduction to PL/SQL
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
 
PLSQL
PLSQLPLSQL
PLSQL
 
PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts
 
Java jdbc
Java jdbcJava jdbc
Java jdbc
 
Laurens Van Den Oever Xopus Presentation
Laurens Van Den Oever Xopus PresentationLaurens Van Den Oever Xopus Presentation
Laurens Van Den Oever Xopus Presentation
 
Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)
 
The Making of the Oracle R2DBC Driver and How to Take Your Code from Synchron...
The Making of the Oracle R2DBC Driver and How to Take Your Code from Synchron...The Making of the Oracle R2DBC Driver and How to Take Your Code from Synchron...
The Making of the Oracle R2DBC Driver and How to Take Your Code from Synchron...
 
Relational Database Management System
Relational Database Management SystemRelational Database Management System
Relational Database Management System
 
Intro to Laravel 4
Intro to Laravel 4Intro to Laravel 4
Intro to Laravel 4
 
Prashanthi
PrashanthiPrashanthi
Prashanthi
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's Code
 
Vision_Academy_Ajava_final(sachin_sir9823037693)_22.pdf
Vision_Academy_Ajava_final(sachin_sir9823037693)_22.pdfVision_Academy_Ajava_final(sachin_sir9823037693)_22.pdf
Vision_Academy_Ajava_final(sachin_sir9823037693)_22.pdf
 
Vision_Academy_Ajava_final(sachin_sir9823037693)_22 (1).pdf
Vision_Academy_Ajava_final(sachin_sir9823037693)_22 (1).pdfVision_Academy_Ajava_final(sachin_sir9823037693)_22 (1).pdf
Vision_Academy_Ajava_final(sachin_sir9823037693)_22 (1).pdf
 
Jdbc tutorial
Jdbc tutorialJdbc tutorial
Jdbc tutorial
 
Sparkling Water 5 28-14
Sparkling Water 5 28-14Sparkling Water 5 28-14
Sparkling Water 5 28-14
 
22jdbc
22jdbc22jdbc
22jdbc
 
Pre-Con Ed: Using Java to Access Your CA IDMS Databases and Applications
Pre-Con Ed: Using Java to Access Your CA IDMS Databases and ApplicationsPre-Con Ed: Using Java to Access Your CA IDMS Databases and Applications
Pre-Con Ed: Using Java to Access Your CA IDMS Databases and Applications
 
3.java database connectivity
3.java database connectivity3.java database connectivity
3.java database connectivity
 

Recently uploaded

Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 

Recently uploaded (20)

Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 

4. plsql 1

  • 1. 8/19/2016 Vinaya Sawant 1  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.  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 DECLARE (optional) - variable declarations BEGIN (required) - SQL statements - PL/SQL statements or sub-blocks EXCEPTION (optional) - actions to perform when errors occur END; (required)
  • 2. 8/19/2016 Vinaya Sawant 2 Anonymous DECLARE BEGIN -statements EXCEPTION END; Procedure PROCEDURE <name> IS BEGIN -statements EXCEPTION END; Function FUNCTION <name> RETURN <datatype> IS BEGIN -statements EXCEPTION END;  Scalar (char, varchar2, number, date, etc)  Composite (%rowtype)  Reference (pointers)  LOB (large objects)  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.  All variables must be declared before their use.  The assignment statement : = is not the same as the equality operator =  All statements end with a ;
  • 3. 8/19/2016 Vinaya Sawant 3 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; Accept p_price Prompt 'Enter the Price: ' DECLARE v_inv_value number(8,2); v_price number(8,2); v_quantity number(8,0) := 400; BEGIN v_price := &p_price; v_inv_value := v_price * v_quantity; dbms_output.put_line('******'); dbms_output.put_line('price * quantity='); dbms_output.put_line(v_inv_value); END; Note: PL/SQL not designed for user interface programming 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; -- nice raise END; -- end of program 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;
  • 4. 8/19/2016 Vinaya Sawant 4  Consider Students table with columns (sid, fname, lname, major, gpa) DECLARE v_max_gpa number(3,2); v_numstudents number(4); v_lname students.lname%type; 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 from students where gpa = v_max_gpa; IF v_numstudents > 1 then DBMS_OUTPUT.PUT_LINE ('There are '||v_numstudents||' with that GPA'); ELSE select lname, major into v_lname, v_major from students 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; / Display the highest GPA Retrieve the no. of students with highest GPA If no. of students are more than 1, then display the count or else display the lname and major of the hisghest GPA scorer. 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; /  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;
  • 5. 8/19/2016 Vinaya Sawant 5  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  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.  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.  cursorname%ROWCOUNT Rows returned so far  cursorname%FOUND One or more rows retrieved  cursorname%NOTFOUND No rows found  Cursorname%ISOPEN Is the cursor open
  • 6. 8/19/2016 Vinaya Sawant 6  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 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; 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; / Write a procedure using cursor to display all tablenames from user tables of Oracle database
  • 7. 8/19/2016 Vinaya Sawant 7 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 something is too complicated for SQL  When conditional branching and looping are needed  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 Query Close Connect Process results
  • 8. 8/19/2016 Vinaya Sawant 8 Query Close Connect Process results Register the driver Connect to the database  Is an interpreter that translates JDBC method calls to vendor-specific database commands  Implements interfaces in java.sql  Can also provide a vendor’s extensions to the JDBC standard Driver JDBC calls Database commands Database  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 Applet JDBC Client Server Thin driver  Written entirely in Java  Applets must use this driver
  • 9. 8/19/2016 Vinaya Sawant 9 Client Server Oracle Application JDBC OCI driver ocixxx.dll  Written in C and Java  Must be installed on the client  JDBC-ODBC Bridge ◦ Translates JDBC into open database connectivity (ODBC) calls ◦ Allows communication with existing ODBC drivers when no JDBC driver is available jdbc:<subprotocol>:<subname> Protocol Database identifier jdbc:oracle:<driver>:@<database> Subprotocol  JDBC uses a URL to identify the database connection.  Thin driver  OCI driver jdbc:oracle:thin:@<host>:<port>:<SID> jdbc:oracle:oci8:@<TNSNAMES entry>
  • 10. 8/19/2016 Vinaya Sawant 10 DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver()); Connection conn = DriverManager.getConnection (URL, userid, password); Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:XE", "scott2","tiger"); 2. Connect to the database. 1. Register the driver. Close Connect Query Create a statement Process results Query the database  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 Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery(statement); int count = stmt.executeUpdate(statement); boolean isquery = stmt.execute(statement); 1. Create an empty statement object. 2. Execute the statement.
  • 11. 8/19/2016 Vinaya Sawant 11 Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery ("select RENTAL_ID, STATUS from ACME_RENTALS"); Statement stmt = conn.createStatement(); int rowcount = stmt.executeUpdate ("delete from ACME_RENTAL_ITEMS where rental_id = 1011");  Execute a select statement. • Execute a delete statement. Close Query Step through the results Process results Assign results to Java variables Connect  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. while (rset.next()) { … } String val = rset.getString(colname); while (rset.next()) { String title = rset.getString("TITLE"); String year = rset.getString("YEAR"); … // Process or display the data }  1. Step through the result set.  2. Use getXXX() to get each column value.
  • 12. 8/19/2016 Vinaya Sawant 12 Connect Query Process results Close Close the result set Close the statement Close the connection 1. Close the ResultSet object. 2. Close the Statement object. 3. Close the connection (not necessary for server-side driver). rset.close(); stmt.close(); conn.close();