Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the...

64
Database Programming Contents 1.The Impedance Mismatch 2.JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3.PLSQL: by Prof. James Dullea, VU Slide 1 of 36

Transcript of Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the...

Page 1: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Database Programming

Contents1.The Impedance Mismatch2.JDBC

1. From the Ricardo text2. From the Elmasri/Navathe text3. From the ASU scholars

3.PLSQL: by Prof. James Dullea, VU

Slide 1 of 36

Page 2: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

The Impedance Mismatch It’s the disconnect between the

approach of a database language and that of a conventional programming language in which it’s embedded: the former uses tables (sets of rows), while the latter uses a record at a time.

Note how each of JDBC and PL/SQL addresses this.

Slide 2 of 36

Page 3: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Next up: JDBC From our text: C. Ricardo From the Elmasri/Navathe text From the ASU scholars

Slide 3 of 36

Page 4: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Databases Illuminated

Chapter 13Databases and the Internet

Page 5: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

JDBC API-standard for relational database

access from Java Includes a set of Java classes and

interfaces Oracle and other vendors have

extended functionality Applications are platform independent Can run on a variety of servers and

DBMSs.

Page 6: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

JDBC Application Steps At the start of the application, import the Java classes

import java.sql.*; For Oracle database add

import oracle.jdbc; Load the JDBC drivers. For Oracle,write

Class.forName(“oracle.jdbc.driver.OracleDriver”); Connect to the database using the DriverManager class

-GetConnection method creates a connection object, which

is used for all communicationconn = DriverManager.getConnection("jdbc:oracle:oci8:url”,”yourId”,”you

rpassword”); Use SQL to interact with the database and Java for the

logic in the application program Close the connection object to disconnect from the

database conn.close(); See Figure 13.13

Page 7: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

The Connection Object Has 3 JDBC classes for communicating with database

Statement -for SQL statements with no parameters PreparedStatement precompiled SQL statement – to be executed many times CallableStatement -for executing stored procedures

Has 3 methods to create instances of these classes createStatement returns a new Statement object prepareStatement takes an SQL statement, precompiles it, and stores it in a

PreparedStatement object prepareCall for call to a stored procedure; has methods for handling input and

output parameters and executing the procedure;returns a CallableStatement

Statement object is used for executing SQL statements Methods executeUpdate, executeQuery. etc. executeQuery method executes an SQL statement and returns a ResultSet

object ResultSet class has many useful methods; includes a cursor to present one row

at a time Within a row, columns can be retrieved using a get method

Page 8: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

Chapter 9

Introduction to SQL Programming Techniques

Page 9: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Slide 9- 9

Java Database Connectivity JDBC:

SQL connection function calls for Java programming

A Java program with JDBC functions can access any relational DBMS that has a JDBC driver

JDBC allows a program to connect to several databases (known as data sources)

Page 10: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Slide 9- 10

Steps in JDBC Database Access

1. Import JDBC library (java.sql.*)2. Load JDBC driver:

Class.forname(“oracle.jdbc.driver.OracleDriver”)3. Define appropriate variables4. Create a connect object (via getConnection)5. Create a statement object from the Statement class:

1. PreparedStatment 2. CallableStatement6. Identify statement parameters (designated by question

marks)7. Bound parameters to program variables8. Execute SQL statement (referenced by an object) via

JDBC’s executeQuery9. Process query results (returned in an object of type

ResultSet) ResultSet is a 2-dimentional table

Page 11: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Slide 9- 11

Embedded SQL in Java:An Example

ssn = readEntry("Enter a SSN: ");

try {

#sql{select FNAME< LNAME, ADDRESS, SALARY

into :fname, :lname, :address, :salary

from EMPLOYEE where SSN = :ssn};

}

catch (SQLException se) {

System.out.println("SSN does not exist: ",+ssn);

return;

}

System.out.println(fname + " " + lname + … );

Page 12: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

WEB/DB 12

ADVANCED DATABASE CONCEPTS JDBC

Susan D. Urban and Suzanne W. DietrichDepartment of Computer Science and Engineering

Arizona State University

Tempe, AZ 85287-5406

Page 13: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

WEB/DB 13

OPEN DATABASE CONNECTIVITY (ODBC)

Standard application programming interface (API) for accessing a database.

A separate module or driver is required for each database to be accessed.

Based on the standard Call Level Interface (CLI) of the SQL Access Group (part of the X/Open Standard).

Can use the API to execute SQL statements, update tables, and retrieve metadata.

Page 14: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

WEB/DB 14

ODBC ISSUES IN A JAVA ENVIRONMENT

ODBC uses C to access the data source. This poses issues with implementation. Hence, it cannot be used in conjunction with Java.

OBDC’S API cannot be used by translating the API to Java since there is no pointer concept in Java.

ODBC requires the driver manager to be installed on every client installation.

Page 15: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

WEB/DB 15

JAVA DATABASE CONNECTIVITY (JDBC)

Java API for connecting programs written in Java to databases.

Based on ODBC. Allows Java programs to send SQL statements

to any relational database. Platform independent. JDBC drivers written in Java can be accessed

from any computer in a heterogeneous network .

A JDBC-ODBC bridge can be used to access databases using the ODBC interface.

Page 16: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

WEB/DB 16

TWO-TIER JDBC ARCHITECTURES

Java application or applet talks directly to the data source. Client sends requests to the server through user interfaces. JDBC Driver communicates with the data source to access the

data.

Sun Microsystems Inc. 1999

Page 17: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

WEB/DB 17

THREE-TIER JDBC ARCHITECTURES

Uses a third tier between the client and the server. Controls updates that are made to the database. Secure and robust.

Sun Microsystems Inc. 1999

Page 18: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

WEB/DB 18

DEVELOPING JDBC APPLICATIONS

Import JDBC classes (java.sql.*) Load the JDBC Driver. Connect to the database. Use the JDBC API to access the database. Disconnect from the database.

Page 19: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

WEB/DB 19

ESTABLISHING A CONNECTION

TO A DATABASE The first step in accessing data from any relational

database using JDBC is to establish a connection with the data source.

The Connection object is used to get meta data and execute SQL statements.

The getConnection method returns a Connection object that represents a session with a specific database.

The parameters in the getConnection method are URL, username and password. Username and password are optional.

The URL consists of the protocol “jdbc”, sub-protocol “odbc”, and the Data Source Name (DSN).

Page 20: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

WEB/DB 20

EXAMPLE TO CONNECT TO A DATABASE

/* dbName is the registered name of the ODBC data source */

String url = "jdbc:odbc:" + dbName ;

try { /* Load the jdbc-odbc driver */ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); /* Open a connection to the odbc data source */ con =DriverManager.getConnection(url,"",""); }

Page 21: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

WEB/DB 21

STATEMENTS

A Statement Object is used to send SQL queries to a database.

A Statement object should be created using the connection method createStatement().

Page 22: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

WEB/DB 22

TYPES OF STATEMENTS

There are three types of statement objects: Simple statements

Used to execute SQL statements without any parameters. Statement stmt = connection.createStatement();

Prepared StatementsUsed when a statement will be called several times and is stored as a pre-compiled statement with IN parameters. PreparedStatement pstmt = con.prepareStatement(“update employee set salary=? where ssn=?”);

Callable StatementsUsed with calls to database stored procedures and SQL statements with OUT parameters.

Page 23: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

WEB/DB 23

EXECUTING SIMPLE STATEMENTS

The execution of a statement returns results into a ResultSet object. The ResultSet object is then used to access query results.

ResultSet rs = null;

The executeQuery() method is used to execute an SQL statement through the statement object.

rs = stmt.executeQuery("SELECT a, b, c FROM Table1"); The close() method is used to close the

ResultSet.rs.close();

Page 24: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

WEB/DB 24

GETTING DATA FROM A ResultSet

The next() method is used to traverse through tuples in the ResultSet object.

The data stored in a ResultSet object is retrieved through a set of get methods that allows access to the various columns of the current row.

The results are printed out on a screen using the Servlet output stream. while(rs.next()) { out.println(rs.getString(“SSN”)); }

Page 25: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

WEB/DB 25

DATABASE METADATA

Metadata is the information in the database that is associated with the database schema: Table names Column names Column types

The metadata associated with a database can be queried using JDBC.

The metadata associated with the result set object of a statement execution can also be queried.

Page 26: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

WEB/DB 26

DATABASE METADATA RETRIEVAL

Create a metadata object.DatabaseMetaData dbmd ;

Retrieve metadata from the database through the connection established.dbmd = con.getMetaData();

The getTables() method of the metadata object is used to retrieve information about the tables in a database. The information is stored in a result set object. ResultSet rsTables = dbmd.getTables(null, null, null, null);

Page 27: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

WEB/DB 27

GETTING THE METADATA

The getString() method of the ResultSet object is used to locate a specific table. String tableName = rsTables.getString("TABLE_NAME");

The getColumns() method is used to retrieve information about the columns and column types in a table, with the results stored in a ResultSet object.ResultSet rsColumns = dbmd.getColumns(null,null,tableName,null); while (rsColumns.next()) { …

}

Page 28: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Next up: PL/SQL

By Prof. James Dullea

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 28 of 36

Page 29: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL Slide 29 of 36

7 From Prof. Dullea CSC8490

Introduction to PL/SQL

Module 01-9

Revised: June 12, 2005

Dr. James Dullea [email protected]

Page 30: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 30 of 36

Introduction to PL/SQL

What is PL/SQL Why PL/SQL Kinds of PL/SQL BLOCKS

Anonymous or Named Blocks Named Blocks (Stored procedures,

Funtions, Triggers) Exceptions Assignments (2)

Page 31: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 31 of 36

What is PL/SQL

PL/SQL is a sophistical programming language used to access an Oracle database from a various environments.

PL/SQL stands for Procedural Language/SQL.It extends SQL by adding constructs found in other procedural languages, such as: loops, conditional statements, declared variables, accessing individual records one at a time, and many others.

Page 32: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 32 of 36

Why use PL/SQLCompared to SQL, PL/SQL has the procedural constructs that are useful to express a desired process from start to end.

One block of PL/SQL code can bundled several SQL statements together as a single unit. Making less network traffic and improving application performance.

PL/SQL can be integrated with other languages, such as Java, to take advantage of the strongest features of both languages.

Page 33: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 33 of 36

Kinds of PL/SQL BLOCKSThe basic unit in any PL/SQL PROGRAM is a BLOCK. All PL/SQL programs are composed of a single block or blocks that occur either sequentially or nested within another block. There are two kinds of blocks:

Anonymous blocks are generally constructed dynamically and executed only once by the user. It is sort of a complex SQL statement.

Named blocks are blocks that have a name associated with them, are stored in the database, and can be executed again and again, can take in parameters, and can modify and existing database.

Page 34: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 34 of 36

Structure of Anonymous Block

DECLARE/* Declare section (optional). */

BEGIN/* Executable section (required). */

EXCEPTION/* Exception handling section

(optional). */

END; -- end the block (do not forget the “ ; “ in the end.)

/

Page 35: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 35 of 36

Example of Anonymous BlockSET SERVEROUTPUT ONDECLARE v_last_name VARCHAR2(15); v_salary employee.salary%TYPE; CURSOR c_query IS SELECT lname, salary FROM employee; BEGIN OPEN c_query; LOOP FETCH c_query INTO v_last_name, v_salary; IF v_salary >= 40000 THEN DBMS_OUTPUT.PUT_LINE (v_last_name||' '||v_salary); END IF; EXIT WHEN c_query%NOTFOUND; END LOOP; CLOSE c_query;END; /

Page 36: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 36 of 36

PL/SQL Build-In Utility PackagesDBMS_OUTPUT.PUT_LINE

SET SERVEROUTPUT ON to allow output to be displayed to the screen

DBMS_OUTPUT.PUT_LINE Usage: DBMS_OUTPUT.PUT_LINE ( Argument ) Argument tendS to resemble the

concatenated arguments of the SELECT clause in an SQL query.

If the argument is not initialized, then a NULL VALUE will be displayed.

Page 37: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 37 of 36

PL/SQL Build-In Utility Packages Example

SET SERVEROUTPUT ONDECLARE v_name VARCHAR2(30); v_title VARCHAR2(20);BEGIN v_name := 'James Dullea'; v_title := 'Research Scientist'; DBMS_OUTPUT.PUT_LINE(v_name||' works as a '||

v_title);END;/

Page 38: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 38 of 36

Variables and TypesA variable is a storage location that can be

read from or assigned to by the program.

It is declared in the declarative section within a PL/SQL block.

v_last_name VARCHAR2(15);

Every variable has a specific data type associated with it. Variables can be associated with a table structure.

v_salary employee.salary%TYPE;

Page 39: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 39 of 36

Data TypesScalar type Numeric: INT,

DEC,NUMBER,BINARY_INTEGER…Character: CHAR, CHARACTER, STRING, VARCHAR, VARCHAR2…Boolean: TRUE, FALSE.Date: DATE

Composite types RECORD, TABLE, VARRAY

Reference types CURSORS, OBJECT TYPES

Lob types BFILE, LOB, CLOB, NLOB

Page 40: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 40 of 36

CURSORS A cursor is used to process a single row

'at a time' from multiple rows retrieved from the database .

Cursors are declared in the Declaration Section.

CURSOR c_query IS SELECT lname, salary FROM employee;

The cursor can be declared for complex queries involving joins and conditions.

Cursors must be OPENed to be accessed and CLOSEd before ending the program.

OPEN c_query; CLOSE c_query;

Page 41: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 41 of 36

CURSORS The FETCH statement is used to

retrieve the output of a single record from the CURSOR SELECT statement INTO associate variables.

FETCH c_query INTO v_last_name, v_salary; Cursors can be opened and closed

more than once in a block and if the a WHERE statement exists, the values of the binding variables can be modified.

“Cursor FOR loop” is a special type of for loop which the SQL cursor operations are carried out implicitly.

Page 42: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 42 of 36

Conditional Statements

Conditional Processing

The specifiedconditions areevaluated by thesystem and the resultdetermines whichsequence ofstatements is to becarried out.

IF <boolean expression> THEN <sequence of statements>END IF;---------------------------------------------------------------------------------------------

IF <boolean expression> THEN <sequence of statements>ELSE<sequence of statements>END IF;

Page 43: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 43 of 36

Conditional Statements (ELSIF)

IF <boolean expression> THEN <sequence of statements>ELSIF <boolean expression> THEN<sequence of statements>ELSIF <boolean expression> THEN<sequence of statements>ELSIF <boolean expression> THEN<sequence of statements>ELSE<sequence of statements>END IF;

Page 44: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 44 of 36

Loop Structures

Unconstrained loops WHILE loop FOR loop GOTO <<LABEL>>

Page 45: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 45 of 36

Unconstrained Loops

LOOP <sequence of

statements> EXIT WHEN

<condition><sequence of

statements> END LOOP;

Page 46: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 46 of 36

WHILE LOOP

WHILE <condition> LOOP

<statements> END LOOP; Note: The loop will continue to

process as long as the condition is TRUE or an EXIT (or EXIT WHEN) statement is encountered.

Page 47: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 47 of 36

FOR LOOP

FOR <loop_counter> IN [REVERSE] <low bound>..<high bound> LOOP <sequence of statements> END LOOP;

Page 48: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 48 of 36

GOTO statement GOTO label;The label is defined in the block bybeing enclosed in double angle brackets.

Example:LOOP<sequence of statements>IF <condition> THENGOTO get_out_of_loop;<sequence of statements>END LOOP;<<get_out_of_loop>>

Page 49: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 49 of 36

NAMED BLOCKSThe following are types of NAMED BLOCKS Stored Procedures

Similar to an anonymous block except it can be stored in the database, can accept parameters, and can be executed over and over again (with different parameters)

Functions Type of named blocks that is executed within a

DML or SQL statement. It may take in one or more parameters and RETURNs only one value back to the calling application.

TriggersA named block that executes only when an

associated DML statement is executed, such as an INSERT, UPDATE, or DELETE statement.

Page 50: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 50 of 36

Block Structure for PL/SQL Subprograms (Procedures or

Functions)

Program Comments (optional) Header (mandatory) IS|AS (mandatory) Declaration Section BEGIN (mandatory) Executable Section EXCEPTION (optional) Exception Section END; (mandatory) /

Page 51: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 51 of 36

Block Structure for PL/SQL subprograms

Completed procedure exampleCREATE OR REPLACE PROCEDURE AddDepartment/*Procedure to add rows In the COMPANY.department table */(p_DepartmentName IN department.dname%TYPE, p_DepartmentNumber IN department.dnumber%TYPE, p_DepartmentManager IN department.mgrssn%TYPE, p_ManagerStartDate IN department.mgrstartdate%TYPE) AS BEGININSERT INTO DEPARTMENT(dname, dnumber, mgrssn, mgrstartdate)VALUES (p_DepartmentName, p_DepartmentNumber, p_DepartmentManager,

p_ManagerStartDate);COMMIT;END AddDepartment;/

 

Page 52: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 52 of 36

Execution of a Stored Functions

EXEC AddDepartment ('Info Center', 43, '888665555', '28-JUN-2005');

Page 53: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 53 of 36

Syntax of a Stored FunctionsCREATE OR REPLACE FUNCTION function_name(parameters IN datatypes)RETURN datatype IS|AS

Declaration SectionBEGIN

Executable SectionRETURN variable_nameEXCEPTION (optional)

Exception SectionEND;

Page 54: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 54 of 36

Example of a Stored Functions

Given the salary of an employee, calculate the state tax of 2.8% from the salary and return it.

Page 55: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 55 of 36

Example of a Stored Functions

CREATE OR REPLACE FUNCTION CalcStateTax ( p_salary IN employee.salary%TYPE) RETURN NUMBERASBEGIN RETURN (p_salary * 0.028);END CalcStateTax;/

Page 56: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 56 of 36

Execution of a Stored Functions

SELECT fname||' '||lname AS "EMPLOYEE", CalcStateTax(salary) AS "STATE TAX"FROM employee;

Page 57: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 57 of 36

Execution of a Stored Functions

EMPLOYEE STATE TAX

------------------------------- ----------

James Borg 1540

Jennifer Wallace 1204

Franklin Wong 1120

John Smith 840

Alicia Zelaya 700

Ramesh Narayan 1064

Joyce English 700

Ahmad Jabbar 700

8 rows selected.

Page 58: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 58 of 36

What is a TriggerSimilar to stored procedures and functions. Contains a Declaration, Executable, and

Exception sectionsDifferences Triggers are not executed explicitly, they are

implicitly execute when a triggering event occurs. (This is called firing the trigger)

Triggers do not accept parameters Triggering events are fired by DML

Statements ( INSERTs, UPDATEs, or DELETEs) against tables or views AND certain system events

Page 59: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 59 of 36

Why Use Triggers Complex integrity constraints are not

always possible through declarative constraints enabled at table creation time, such as salary may not be lowered.

Auditing information, such as who updated an employee's salary, may be required. Remember triggers happen at the basic DML level.

Triggers can signal other application that action needs to take place when changes are made to a table. Example, update employee statistics contained in another table.

Page 60: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 60 of 36

Block Structure for a PL/SQL Trigger

CREATE [OR REPLACE] TRIGGER trigger_nameAFTER | BEFORE | INSTEAD OF a_trigger_eventON table_name (or view_name) [FOR EACH ROW[WHEN trigger_condition]]DECLARE (optional)BEGIN (mandatory)

Executes only when trigger_condition is TRUE on a ROW LEVEL TRIGGER

EXCEPTION (optional)Exception Section

END; (mandatory) NOTE: a_trigger_event may be any combination of

an INSERT, DELETE, and/or UPDATE on a table or view

Page 61: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 61 of 36

Errors and Error Handling Errors can be classified into two types:

1) Compile-Time errors and warnings.

After compiling use the command

SHOW ERRORS

use SET ECHO ON to see statement

numbers

2) Run-Time errors occur during execution

and throw exception that can be handled by

the program.

Page 62: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 62 of 36

Error Handling

When errors occur during the execution, control will be branched to the exception handling section.

A corresponding error handler will be

found to deal with the error.

Page 63: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 63 of 36

Practice 1Use the Company database schema, write a stored

procedure to add an employee to the employee table, using parameters to input the data. Use your name and following information to test the procedure.

FNAME use your first name

MINIT use your middle init or a blank space

LNAME use your last name

SSN make up a 9 digit number

BDATE use your birthday (be careful of the date format)

STREET make up data

CITY Villanova

STATE PA

ZIP use the Villanova zip code

SEX M or F

SALARY 38000

SUPERSSN 333445555

DNO 5

Page 64: Database Programming Contents 1. The Impedance Mismatch 2. JDBC 1. From the Ricardo text 2. From the Elmasri/Navathe text 3. From the ASU scholars 3. PLSQL:

Dr. James Dullea, CSC8490 Introduction to PL/SQL

Slide 64 of 36

Practice 2Write a function (called GetDay) that will take in a

date as a parameter and return the actual name of the day for that date. Use the function to solve the following problem.

Using the data in the employee table from Assignment 1, write an SQL statement or an anonymous block (containing the above function GetDay) that uses your first and last name in a where clause to access the record and returns the actual day of the week that you were born. Hint: GetDay(bdate)