Sunteți pe pagina 1din 62

CSC352/CSC452

Database Programming
Instructor: Lu Zhang, Ph.D.

Email: lzhang@cs.depaul.edu
Office Hours: Monday 4:30 5:30 PM
Monday after class

Prerequisite:
1. CSC319/CSC 449 and (CSC212 or
CSC224).
2. Review chapters 1 and 2 in the
textbook.

CSC452 Database Programming

Textbook and References


Textbook:

Raj Sunderraman, ORACLE9TM Programming:


A Primer, Addison-Wesley

Online Resource:

http://otn.oracle.com/documentation/content.html

Oracle PL/SQL Users Guide and Reference

CSC452 Database Programming

Topics

Oracle PL/SQL

Introduction to PL/SQL
PL/SQL Language Fundamentals
Conditions, Controls, and Loops
Database Interactions and Cursors
Exception Handlers
Debugging
Procedures and Functions
Packages
PL/SQL and SQL Interactions

Triggers
PL/SQL Best Practices
JDBC API that enables database access
in Java
SQLJ Embedded SQL with Java

CSC452 Database Programming

Topics

What this course is about

What this course is not about

CSC452 Database Programming

Grading
Homework/Project: 40% (Late assignments will
be accepted but will be penalized at 16.67% per
day.)
Mid Term: 30% (in-class week 7)
Final: 30% (take-home)
Grades will be assigned based on the following
scale:
A: 90 - 100
B: 80 - 89
C: 70 79
D: 60 69, and
F: 59 and below
The "+" and "-" grade extensions will be used at the
instructor's discretion. Note, however, this does not
elevate grades.

CSC452 Database Programming

Expectations

Attendance

Classroom participation

Classroom behavior

Homework

Prerequisites

lack of prerequisites might prevent you from fully


mastering the content and affect your overall
grade!
CSC452 Database Programming

Course On Line

Notes
Homework
Projects
Announcements
Grades
Graders email
etc.

CSC452 Database Programming

About Email
Make sure that your email address is
current and correct in the system
For yahoo and hotmail users, make sure
that your account is not over the quota
What and how should I email?
What shouldnt I email?

CSC452 Database Programming

Programming Environment

Hawk and Oracle Account


Hawk
telnet hawk.depaul.edu

change password

hawk% passwd (Change password.)


Changing password for xxxxxx
Old password: xxxxxxx
New password: xxxxxxx (Not echoed to screen.)
Verification: xxxxxxx (Not echoed to screen.)

.login file add the following line


logout

source /usr/local/oracle.csh
hawk% exit

CSC452 Database Programming

Programming Environment

Some Useful UNIX commands

ls
ls la
mkdir <dir-name>
cd <dir-name>
pwd
cd..
cp <file1> <file2>
mv <file1> <file2>
passwd
rm <file1>
rmdir
rm r <dir>
cat <file1>
more <file1>

list the file in that directory


list files (include hidden ones) in details
make a new directory
change directory
show the current working directory
go up one level of the directory
copy file1 to file2
rename file1 to a new name: file2
change UNIX password
delete file1
delete directory and all its contents
delete directory
display the contents of file1
display contents of file1 one page at a time

CSC452 Database Programming

Programming Environment

Hawk and Oracle Account


Oracle:to connect to Oracle, type sqlplus after
the prompt
hawk% sqlplus
You will then be prompted for your Oracle username and
password. Once you have successfully logged into
Oracle, youll get the prompt:
SQL>

To change your Oracle password, execute the


following SQL command:
SQL> password

Then follow the instructions.


Disconnect from ORACLE
SQL> exit

CSC452 Database Programming

Programming Environment

Hawk and Oracle Account


Useful sqlplus commands:
1. To get help:
e.g.,

SQL> help commands


SQL> help save

2.

To run an SQL command, type the SQL


statement followed by a semi-colon (;):
SQL> select * from myTable;

or by entering a slash (/) on a separate line


by itself:
SQL> select * from myTable
SQL> /

3.

To run a command saved in the buffer:


SQL> run

CSC452 Database Programming

Programming Environment

Hawk and Oracle Account


Useful sqlplus commands:
4. If you wish to save your SQL statement, you
can save it to a file (e.g., mySQLstatement.sql)
by the following command:
SQL> save mySQLstatement

5.

You can edit saved SQL statements


SQL> edit

6.

To read/fetch the SQL statement you have


saved in a file (e.g., mySQLstatement), do the
following:
SQL> get mySQLstatement

and run it by type in / followed by the ENTER


key
CSC452 Database Programming

Programming Environment

Hawk and Oracle Account


Useful sqlplus commands:
7. Executing SQL statements saved in a file
(e.g., mySQLstatement.sql), do the following:
SQL> start mySQLstatement
8.

You can save the output from your SQL


statements to a file by using the spool
command:
SQL> spool file_name

It continues to spool until you turn it off by:


SQL> spool off
CSC452 Database Programming

Programming Environment

Hawk and Oracle Account


Transferring files
ftp ftp hawk.depaul.edu
cd change directories on the remote machine
lcd change directories on the local machine
put transfer files from the local machine to
the remote machine
get transfer files from the remote machine
to the local machine
mput transfer multiple files from the local
machine to the remote machine
mget transfer multiple files from the remote
machine to the local machine
prompt
CSC452 Database Programming

Programming Environment

Oracle Installed on Local PC


connect to local Oracle

CSC452 Database Programming

Programming Environment

Oracle Installed on Local PC


connect to local Oracle

CSC452 Database Programming

Programming Environment

Oracle Installed on Local PC


connect to local Oracle

CSC452 Database Programming

Programming Environment

Oracle Installed on Local PC


connect to remote Hawk Oracle account net service

CSC452 Database Programming

# TNSNAMES.ORA Network Configuration File: C:\oracle\ora90\network\admin\tnsnames.ora


# Generated by Oracle configuration tools.

INST1_HTTP.CSTCIS.CTI.DEPAUL.EDU =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = lzhanglap)(PORT = 1521))
)
(CONNECT_DATA =
(SERVER = SHARED)
(SERVICE_NAME = MODOSE)
(PRESENTATION = http://HRService)
)
)
EXTPROC_CONNECTION_DATA.CSTCIS.CTI.DEPAUL.EDU =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC0))
)
(CONNECT_DATA =
(SID = PLSExtProc)
(PRESENTATION = RO)
)
)
LAPTOP.CSTCIS.CTI.DEPAUL.EDU =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = lzhanglap)(PORT = 1521))
)
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = LAPTOP)
)
)

# TNSNAMES.ORA Network Configuration File: C:\oracle\ora92\network\admin\tnsnames.ora


# Generated by Oracle configuration tools.
INST1_HTTP.CSTCIS.CTI.DEPAUL.EDU =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = lzhanglap)(PORT = 1521))
)
(CONNECT_DATA =
(SERVER = SHARED)
(SERVICE_NAME = MODOSE)
(PRESENTATION = http://HRService)
)
)
EXTPROC_CONNECTION_DATA.CSTCIS.CTI.DEPAUL.EDU =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC0))
)
(CONNECT_DATA =
(SID = PLSExtProc)
(PRESENTATION = RO)
)
)
STUDENT.CSTCIS.CTI.DEPAUL.EDU =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = hawk.depaul.edu)(PORT = 1521))
)
(CONNECT_DATA =
(SERVICE_NAME = student.dpu)
)
)
LAPTOP.CSTCIS.CTI.DEPAUL.EDU =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = lzhanglap)(PORT = 1521))
)
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = LAPTOP)
)
)

Programming Environment

Oracle Installed on Local PC


connect to remote Hawk Oracle account - net service

CSC452 Database Programming

Programming Environment

Tools
SQL Navigator (server side only)
DBArtisan
etc.

CSC452 Database Programming

Programming Environment

Homework - dont need to turn in

Review relational database concepts and


SQL. Read chapters 1 and 2 of the
textbook.
Try to set up your programming
environment, log into your Oracle account,
and practice the various SQLplus
commands.

Assignment #1 (see COL) need to turn in


CSC452 Database Programming

Introduction to PL/SQL

What Is PL/SQL?

PL/SQL stands for

Procedural Language extensions to SQL

combines the data manipulating power of


SQL with the data processing power of
procedural languages.

CSC452 Database Programming

Introduction to PL/SQL

What Is PL/SQL?
PL/SQL, Oracles procedural extension of
SQL, is an advanced fourth-generation
programming language (4GL). It offers modern
features such as data encapsulation,
overloading, collection types, exception
handling, and information hiding. PL/SQL also
offers seamless SQL access, tight integration
with the Oracle server and tools, portability,
and security. Oracle PL/SQL Users Guide
and Reference

CSC452 Database Programming

Introduction to PL/SQL

Readings: Chapter 4

What Is PL/SQL?
1. Design features of programming languages.
2. Data manipulation and query statements (i.e.,
SQL) capabilities (are included within
procedural units of code.)
3. Interactions between programming language
constructs and SQL

CSC452 Database Programming

Introduction to PL/SQL

Readings: Chapter 4

What Is PL/SQL? (Main Features of PL/SQL)


(IMPLICIT)
CURSOR

FLOW
CONTROL

ERROR
HANDLING

DECLARE
VARIABLES
qty_on_hand NUMBER(5);
BEGIN
SELECT quantity INTO qty_on_hand FROM inventory
WHERE product = TENNIS RACKET FOR UPDATE OF quantity;
IF qty_on_hand > 0 THEN -- check quantity
UPDATE inventory SET quantity = quantity - 1
SQL STATEMENT
WHERE product = TENNIS RACKET;
INSERT INTO purchase_record
VALUES (Tennis racket purchased, SYSDATE);
ELSE
INSERT INTO purchase_record
VALUES (Out of tennis rackets, SYSDATE);
END IF;
COMMIT;
EXCEPTION
WHEN NO_DATA_FOUND THEN
INSERT INTO temp VALUES (NULL, NULL, Not found);
COMMIT;
END;

CSC452 Database Programming

Introduction to PL/SQL

What Is PL/SQL? (Main Features of PL/SQL)


PL/SQL is a block-structured language. PL/SQL procedures,
functions, and anonymous blocks (the basic unit of PL/SQL) are all
block-structure based. In PL/SQL, blocks can contain any number
of nested sub-blocks. You can nest sub-blocks in the executable
and exception-handling parts of a PL/SQL block or subprogram
but not in the declarative part. Also, you can define local
subprograms in the declarative part of any block. However, you
can call local subprograms only from the block in which they are
defined. Typically, each block corresponds to a problem or
subproblem to be solved (divide and conquer)

CSC452 Database Programming

Introduction to PL/SQL

What Is PL/SQL? (Main Features of PL/SQL)

Block Structure

[BLOCK HEADER
IS]
[DECLARE
-- declarations]
BEGIN
-- statements
[EXCEPTION
-- handlers]
END;

CSC452 Database Programming

Block Header (optional)


Declarative Part (optional)
- local to the block only
Executable Part (required)
Exception-Handling
Part (optional)
Required

Introduction to PL/SQL

What Is PL/SQL? (Main Features of PL/SQL)

Variables and Constants


Declaring Variables

part_no NUMBER(4);
in_stock BOOLEAN;
Variables can have any SQL data types such as CHAR, DATE,
or NUMBER, or any PL/SQL data type such as BOOLEAN or
BINARY_INTEGER. You can also declare nested tables,
variable-size arrays (varrays for short), and records using the
TABLE, VARRAY, and RECORD composite datatypes.

CSC452 Database Programming

Introduction to PL/SQL

What Is PL/SQL? (Main Features of PL/SQL)

Variables and Constants


Assigning Values to Variables (three different
ways)
1. part_no := 1001;
in_stock := TRUE;

2. SELECT pno INTO part_no FROM part


WHERE color = red;
3. DECLARE
my_sal REAL(7,2);
PROCEDURE adjust_salary (emp_id INT, salary IN OUT REAL)
IS ...
BEGIN
SELECT AVG(sal) INTO my_sal FROM emp;
adjust_salary(7788, my_sal); -- assigns a new value to my_sal
CSC452 Database Programming

Introduction to PL/SQL

What Is PL/SQL? (Main Features of PL/SQL)

Variables and Constants


Declaring Constants

Declaring a constant is like declaring a variable


except that you must add the keyword CONSTANT
and immediately assign a value to the constant.
Thereafter, no more assignments to the constant
are allowed.
credit_limit CONSTANT REAL := 5000.00;
CSC452 Database Programming

Introduction to PL/SQL

What Is PL/SQL? (Main Features of PL/SQL)

Variables and Constants


In PL/SQL, variables and constants must be
declared before they are been referenced.
Forward references are not allowed. The
declarations are local to the block and cease to
exist when the block completes.

CSC452 Database Programming

Introduction to PL/SQL

What Is PL/SQL? (Main Features of PL/SQL)

Cursors
Oracle uses work areas to execute SQL statements
and store processing information. A cursor lets you
name a work area and access its stored information.
You can use the OPEN, FETCH, and CLOSE
statements or the Cursor For loops to control
cursors.
cursor

1
2
3
4
5

Jane
John
Jack
Jill
Jesse

CSC452 Database Programming

Doe
Doe
Doe
Doe
Doe

current row

Introduction to PL/SQL

What Is PL/SQL? (Main Features of PL/SQL)

Attributes

%TYPE declares variables according to:


- A database column definition
- Another previously declared variable
v_ename
v_data
v_total_data

emp.name%TYPE;
NUMBER(20, 2);
v_data%TYPE;

%ROWTYPE declares variables according to rows in database


tables
v_employee

employee%ROWTYPE;

CSC452 Database Programming

Introduction to PL/SQL

What Is PL/SQL? (Main Features of PL/SQL)

Attributes

Advantages:
1. dont need to know the exact data type of the
underlying database column, and
2. if the data type of the underlying database
column or the variable an attribute references got
changed, the data type of the attribute changes
accordingly at run time.

CSC452 Database Programming

Introduction to PL/SQL

What Is PL/SQL? (Main Features of PL/SQL)

Control Structures

Conditional Control
1. IF-THEN-ELSE statements
2. CASE statements
Iterative Control
1. Loop statements
2. For-loop statements
3. While-loop statements
Sequential Control
1. Goto statements
CSC452 Database Programming

Introduction to PL/SQL

What Is PL/SQL? (Main Features of PL/SQL)

Modularity

Procedures and Functions named PL/SQL blocks


PROCEDURE award_bonus (emp_id NUMBER) IS
bonus REAL;
comm_missing EXCEPTION;
BEGIN -- executable part starts here
SELECT comm * 0.15 INTO bonus FROM emp WHERE empno = emp_id;
IF bonus IS NULL THEN
RAISE comm_missing;
ELSE
UPDATE payroll SET pay = pay + bonus WHERE empno = emp_id;
END IF;
EXCEPTION -- exception-handling part starts here
WHEN comm_missing THEN
...
END award_bonus;
CSC452 Database Programming

Introduction to PL/SQL

What Is PL/SQL? (Main Features of PL/SQL)

Block Structure

[BLOCK HEADER
IS]
[DECLARE
-- declarations]
BEGIN
-- statements
[EXCEPTION
-- handlers]
END;

CSC452 Database Programming

Block Header (optional)


Declarative Part (optional)
- local to the block only
Executable Part (required)
Exception-Handling
Part (optional)
Required

Introduction to PL/SQL

What Is PL/SQL? (Main Features of PL/SQL)

Modularity

A package is a PL/SQL construct that allows related objects


to be stored together. Packages are used to bundle logically
related types, variables, cursors, and subprograms.
CREATE PACKAGE emp_actions AS -- package specification
PROCEDURE hire_employee (empno NUMBER, ename CHAR, ...);
PROCEDURE fire_employee (emp_id NUMBER);
END emp_actions;
CREATE PACKAGE BODY emp_actions AS -- package body
PROCEDURE hire_employee (empno NUMBER, ename CHAR, ...) IS
BEGIN
INSERT INTO emp VALUES (empno, ename, ...);
END hire_employee;
PROCEDURE fire_employee (emp_id NUMBER) IS
BEGIN
DELETE FROM emp WHERE empno = emp_id;
END fire_employee;
END emp_actions;

CSC452 Database Programming

Introduction to PL/SQL

What Is PL/SQL? (Main Features of PL/SQL)

Data Abstraction and Information Hiding

Collections
The collection types TABLE and VARRAY works like arrays. A
collection is an ordered group of elements, all of the same
type. Each element has a unique subscript that determines its
position in the collection.
Records
You can use the %ROWTYPE attribute to declare a record
that represents a row in a table or a row fetched from a
cursor. You can declare fields of your own with user-defined
records. You can also nest records. That is, a record can be
a component of another record.
CSC452 Database Programming

Introduction to PL/SQL

What Is PL/SQL? (Main Features of PL/SQL)

Data Abstraction and Information Hiding

Object Types
In PL/SQL, object-oriented programming is based on object
types. An object type encapsulates a data structure along with
the functions and procedures needed to manipulate the data.
The variables that form the data structure are called
attributes. The functions and procedures that characterize the
behavior of the object type are called methods.
CREATE TYPE Bank_Account AS OBJECT (
acct_number INTEGER(5),
balance REAL,
status VARCHAR2(10),
MEMBER PROCEDURE open (amount IN REAL),
MEMBER PROCEDURE verify_acct (num IN INTEGER),
MEMBER PROCEDURE close (num IN INTEGER, amount OUT REAL),
MEMBER PROCEDURE deposit (num IN INTEGER, amount IN REAL),
MEMBER PROCEDURE withdraw (num IN INTEGER, amount IN REAL),
MEMBER FUNCTION curr_bal (num IN INTEGER) RETURN REAL
);

CSC452 Database Programming

Introduction to PL/SQL

What Is PL/SQL? (Main Features of PL/SQL)

Error Handling Exceptions

Exceptions are predefined and user-defined error conditions.


When an error occurs, an exception is raised. That is,
normal execution stops and control transfers to the
exception-handling part of the underlying PL/SQL block or
subprogram. To handle raised exceptions, you write separate
routines called exception handlers.
Predefined exceptions are raised implicitly by the runtime
system. For example, if you try to divide a number by zero,
PL/SQL raises the predefined exception ZERO_DIVIDE
automatically. You must raise user-defined exceptions
explicitly with the RAISE statement.
CSC452 Database Programming

Introduction to PL/SQL

What Is PL/SQL? (Main Features of PL/SQL)

Error Handling Exceptions

DECLARE
...
comm_missing EXCEPTION; -- declare exception
BEGIN
...
IF commission IS NULL THEN
RAISE comm_missing; -- raise exception
END IF;
bonus := (salary * 0.10) + (commission * 0.15);
EXCEPTION
WHEN comm_missing THEN ... -- process the exception

CSC452 Database Programming

Introduction to PL/SQL
PL/SQL Architecture
PL/SQL can reside in two environments:
1. Oracle Database Server
2. Oracle Tools (forms and reports)
Client
Side

3rd Party Application


Development Tools

SQL*Plus

PL/SQL
Programs

PL/SQL
Programs

Server
Oracle Server
Side
PL/SQL Engine
Procedural
Statement
Executor

Oracle Tools (forms and reports)


PL/SQL
Engine

SQL

Stored Program Unit

PL/SQL
Procedural
Block

CSC452 Database Programming

PL/SQL
Programs

SQL

SQL
Statement
Executor

Introduction to PL/SQL

Advantages of PL/SQL
1.
2.
3.
4.
5.
6.
7.

Support for SQL


Support for object-oriented programming
Better performance
Higher productivity
Full portability
Tight integration with Oracle
Tight security

CSC452 Database Programming

Introduction to PL/SQL

Advantages of PL/SQL Better Performance


SQL

Client

SQL

Server

SQL

Client

Client

CSC452 Database Programming

SQL
IF THEN
SQL
ELSE
SQL
END IF;
SQL

RPC

Server

Server
(stored
PL/SQL)

Introduction to PL/SQL

To PL/SQL or Not To PL/SQL?

PL/SQL is Oracle's procedural extension to industrystandard SQL. PL/SQL naturally, efficiently, and
safely extends SQL. Its primary strength is in
providing a server-side, stored procedural language
that is easy-to-use, seamless with SQL, robust,
portable, and secure. Thus, it offers a platform for
robust, high-performing enterprise applications, not
only for our Fortune 500 customers

CSC452 Database Programming

Introduction to PL/SQL
To PL/SQL or Not To PL/SQL?

PL/SQL:
Data centric and tightly integrated into the database
Proprietary to Oracle and difficult to port to other database
systems
Processing is done inside the database engine so it is faster
in PL/SQL than in Java
PL/SQL is a better solution for SQL-intensive applications.
PL/SQL is optimized for SQL, and so SQL operations are
faster in PL/SQL than in Java.
Java:
Open standard, not proprietary to Oracle
Incurs some data conversion overhead between the Database
and Java type systems
is a better solution for logic-intensive applications.
CSC452 Database Programming

S-ar putea să vă placă și