Oracle SQL Tutorial

28
Oracle SQL Tutorial SQL*Plus — schemata — data types — DML & DDL examples — editing commands — using external files — the dual pseudo-table — introduction to transactions — optional exercise — references. Introduction During this tutorial you will build on your databases knowledge by learning the fundamentals of Oracle, one of the most widely used database management system in industry. SQL*Plus SQL*Plus is Oracle's command-line interpreter. You may launch SQL*Plus by issuing the sqlplus command in UNIX or using the `start' menu in Windows. In the `start' menu, SQL*Plus is listed under programs > oracle > application development > SQL Plus You will be prompted for your username and password. If you haven't got an account, you can try to use scott for the username, and tiger for the password. You will learn at a later stage how to change your password. The last piece of information required by SQL*Plus is the name of the database you want to use (called host string). You are now connected to a shared database, on which you have an account (called a schema ). Basic SQL Table 1 outlines the main Oracle SQL data types, together with their MySQL equivalent. Note is the VARCHAR2 type, so called for historical reasons. The NUMBER(p,s) type takes two arguments; precision and scale. The precision of a number its number of significant decimal digits, and its scale is the number of digits after the decimal point. Table 1: The main SQL data types.

description

thats good for student

Transcript of Oracle SQL Tutorial

Page 1: Oracle SQL Tutorial

Oracle SQL Tutorial

SQL*Plus — schemata — data types — DML & DDL examples — editing commands — using external files — the dual pseudo-table — introduction to transactions — optional exercise — references.

Introduction

During this tutorial you will build on your databases knowledge by learning the fundamentals of Oracle, one of the most widely used database management system in industry.

SQL*Plus

SQL*Plus is Oracle's command-line interpreter. You may launch SQL*Plus by issuing the sqlplus command in UNIX or using the `start' menu in Windows. In the `start'

menu, SQL*Plus is listed under programs > oracle > application development > SQL Plus

You will be prompted for your username and password. If you haven't got an account, you can try to use scott for the username, and tiger for the password. You will learn at a later stage how to change your password. The last piece of information required by SQL*Plus is the name of the database you want to use (called host string). You are now connected to a shared database, on which you have an account (called a schema ).

Basic SQL

Table 1 outlines the main Oracle SQL data types, together with their MySQL equivalent. Note is the VARCHAR2 type, so called for historical reasons. The NUMBER(p,s) type takes two arguments; precision and scale. The precision of a number its number of significant decimal digits, and its scale is the number of digits after the decimal point.

Table 1: The main SQL data types.

Type description Oracle SQL MySQL SQL

variable-length char. string VARCHAR2(l)1 VARCHAR(l)

fixed-length char. string CHAR(l) CHAR(l)

number NUMBER(p,s)2 NUMERIC(p,s)

currency NUMBER(10,2) NUMERIC(10,2)

Page 2: Oracle SQL Tutorial

date DATE DATE1 length. 2 precision, scale.

You should now be able to create a few tables and populate them.

CREATE TABLE books

(

title VARCHAR2(60),

author VARCHAR2(60),

isbn NUMBER(10,0)

CONSTRAINT pk_books PRIMARY KEY,

pub_date DATE DEFAULT SYSDATE

)

/

CREATE TABLE book_reviews

(

isbn NUMBER(10,0)

CONSTRAINT fk_books_booksrev REFERENCES books(isbn),

reviewer VARCHAR2(30),

comments VARCHAR2(150)

)

/

Note the use of the SYSDATE function that returns the system's current date in the DEFAULT clause above. The `/' character terminates an SQL statement and submits it to SQL*Plus.

Page 3: Oracle SQL Tutorial

You should be already familiar with the syntax of the primary key  and referential integrity  constraints. They function in Oracle in a similar fashion as in MySQL. pk_books and fk_books_booksrev are constraint names. Now check the schema of the tables you have just created using the desc <table_name> command (same command as in MySQL).

Next, we want to insert some data into books and books_reviews:

INSERT INTO books VALUES

(

'The Importance of Being Earnest',

'Oscar Wilde', -- this is a comment

9876543210,

'14-FEB-1895'

)

/

INSERT INTO book_reviews VALUES

(

9876543210,

'Alice',

'Excellent work, humorous and witty.'

)

/

As shown above, the date format expected by Oracle is DD-MMM-YYYY or DD-MMM-YY. The double hyphen sequence `- -' introduces a comment.

Editing Commands

Editing SQL*Plus' buffer.

As you may already have experienced, you cannot  recall statements after they have been submitted to SQL*Plus. The ed command allows you to edit the SQL*Plus buffer

Page 4: Oracle SQL Tutorial

in the system's default editor. After saving your changes, submit the statement with a `/'. Be aware that only the last  statement submitted  to SQL*Plus may be edited.

Using command files.

A practical approach to avoid inadvertently losing your SQL work is to use command files.

1. type in your SQL statements in your favourite editor. 2. save the file with the .sql extension in your home directory (e.g. myfile.sql)—

make sure that you get the correct extension, as some editors will attempt to append a .txt extension.

3. type in @myfile at the SQL*Plus command prompt to execute your SQL statement(s).

Before starting the next section, you should practise creating and populating some more tables.

SQL Tutorial, Part 2

SQL*Plus — schemata — data types — DML & DDL examples — editing commands — using external files — the dual pseudo-table — introduction to transactions — optional exercise — references.

More Oracle SQL

You are now armed to attempt some more complex SQL expressions.

The dual pseudo-table.

Oracle insists that all  SELECT statements be of the form ``SELECT <attribute> FROM <table>''—even when the returned value does not depend on data stored in the

database. The DUAL pseudo-table was introduced to allow such statements.

SELECT 'Hello' FROM DUAL -- shows 'Hello'

/

SELECT SYSDATE FROM DUAL -- shows the date

/

Sequence numbers.

A SEQUENCE is an Oracle object that generates integers according to a specific pattern.

Sequence numbers are commonly utilised to supply auto-generated primary keys. The default behaviour of a SEQUENCE is to increment its current value by one to get the next.

Page 5: Oracle SQL Tutorial

You may already have used sequences in MySQL, using the AUTO_INCREMENT

attributes. Note however the two differences with Oracle's sequences:

in MySQL, numeric fields using AUTO_INCREMENT need to be declared as such, in Oracle sequences are separate entities

MySQL increments the sequence when required, you do not have to do it explicitly

The following code creates a SEQUENCE that we will then use to insert some more

values in the books table.

CREATE SEQUENCE book_seq

/

INSERT INTO books VALUES

(

'Oliver Twist',

'Charles Dickens',

book_seq.NEXTVAL,

'12-SEP-1839'

)

SELECT book_seq.CURRVAL FROM DUAL -- shows the current value

/

SELECT book_seq.NEXTVAL FROM DUAL -- displays the next value

/

Apart from the the Oracle peculiarities we have already discussed, you can re-use most of your knowledge of SQL. You may want for example to experiment with the UPDATE and DELETE statements.

Introduction to Transactions

Transaction management  is a broad topic to which you have been introduced in the database lectures. You should refer to your notes for a more detailed coverage of the subject, as we will here just remind a few points. A transaction is a logical unit of work , that could be for example the placement of an order. On completion, a transaction needs to be either confirmed —making all the changes permanent—or cancelled —

Page 6: Oracle SQL Tutorial

returning the database into the state it was before starting the transaction. These two actions are performed in SQL by issuing one of the two commands COMMIT or ROLLBACK.

To experiment with transactions, you will need to work in pairs (say Alice and Bob) and allow the other student to read the data in your books table. So Alice will need to enter:

GRANT SELECT ON books TO bob

/

and Bob to enter:

GRANT SELECT ON books TO alice

/

Now Alice should enter some data in her books table. Bob can then attempt to view the newly inserted data by typing:

SELECT * FROM alice.books

/

Note how you can prefix the table name with its schema to reference other students' tables. Can Bob view the changes Alice has made? What happens if Alice COMMITs the transaction? Try also with ROLLBACK. Try to relate your observations with your understanding of transactions.

Optional Exercise Suggestion

ISBNs (International Standard Book Number) are unique, 10-digit book identifiers used in the publishing industry. With the help of the references given at the end of this document, create a sequence to generate 10-digit integers for use with the books table.

References

You can copy & paste the following URIs (note that you will need a username/password to access Oracle's web site. You can use [email protected]/database):

Oracle SQL & standard SQL compared: http://www-db.stanford.edu/~ullman/fcdb/oracle/or-nonstandard.html

Page 7: Oracle SQL Tutorial

Oracle SQL reference: http://download-west.oracle.com/docs/cd/A91202_01/901_doc/server.901/a90125/toc.htm

Oracle SQL*Plus quick reference: http://download-west.oracle.com/docs/cd/B10501_01/server.920/a96525/toc.htm

Oracle error messages: http://download-west.oracle.com/docs/cd/B10501_01/server.920/a96525/toc.htm

PL/SQL Tutorial

Need for PL/SQL — declarative vs. procedural — anonymous blocks — debugging — a first program — code compilation — code execution — procedures & functions — PL/SQL in SQL — SQL in PL/SQL — cursors & loops — operators & built-in functions reference tables.

Introduction

PL/SQL is a database-oriented programming language that extends Oracle SQL with procedural capabilities. We will review in this lab the fundamental features of the language and learn how to integrate it with SQL to help solve database problemsg

Need for PL/SQL

SQL statements are defined in term of constraints we wish to fix on the result of a query. Such a language is commonly referred to as declarative. This contrasts with the so called procedural languages where a program specifies a list of operations to be performed sequentially to achieve the desired result. PL/SQL adds selective  (i.e. if...then...else...) and iterative constructs (i.e. loops) to SQL. PL/SQL is most useful to write triggers  and stored procedures. Stored procedures are units of procedural code stored in a compiled form within the database.

PL/SQL Fundamentals

PL/SQL programs are organised in functions, procedures and packages (somewhat similar to Java packages). There is a limited support for object-oriented programming. PL/SQL is based on the Ada programming language, and as such it shares many elements of its syntax with Pascal.

Your first example in PL/SQL will be an anonymous block —that is a short program that is ran once, but that is neither named nor stored persistently in the database.

Page 8: Oracle SQL Tutorial

SQL> SET SERVEROUTPUT ON

SQL> BEGIN

2 dbms_output.put_line('Welcome to PL/SQL');

3 END;

4 /

SET SERVEROUTPUT ON is the SQL*Plus command1 to activate the console output. You only need to issue this command once in a SQL*Plus session.

the keywords BEGIN...END define a scope  and are equivalent to the curly braces in Java {...}

a semi-column character (;) marks the end of a statement the put_line function (in the built-in package dbms_output) displays a string in the

SQL*Plus console.

You are referred to Table 2 for a list of operators, and to Table 3 for some useful built-in functions.

Compiling your code.

PL/SQL code is compiled by submitting it to SQL*Plus. Remember that it is advisable to type your program in an external editor, as you have done with SQL (see Introduction to Oracle).

Debugging.

Unless your program is an anonymous block,  your errors will not  be reported. Instead, SQL*Plus will display the message ``warning: procedure created with compilation errors''. You will then need to type:

SQL> SHOW ERRORS

to see your errors listed. If yo do not understand the error message and you are using Oracle on UNIX, you may be able to get a more detailed description using the oerr utility, otherwise use Oracle's documentation (see References section). For example, if Oracle reports ``error PLS-00103'', you should type:

oerr PLS 00103

at the UNIX command prompt  (i.e. not in SQL*Plus).

Page 9: Oracle SQL Tutorial

Executing PL/SQL

If you have submitted the program above to Oracle, you have probably noticed that it is executed straight away. This is the case for anonymous blocks, but not for procedures and functions. The simplest way to run a function (e.g. sysdate) is to call it from within

an SQL statement:

SQL> SELECT sysdate FROM DUAL

2 /

Next, we will rewrite the anonymous block above as a procedure. Note that we now use the user function to greet the user.

CREATE OR REPLACE PROCEDURE welcome

IS

user_name VARCHAR2(8) := user;

BEGIN -- `BEGIN' ex

dbms_output.put_line('Welcome to PL/SQL, '

|| user_name || '!');

END;

/

Make sure you understand the changes made in the code:

A variable user_name of type VARCHAR2 is declared user_name is initialised  using the user2 built-in function ``:='' is the assignment  operator (see. Table 2)

Once you have compiled the procedure, execute it using the EXEC command.

SQL> EXEC welcome

Both procedures and functions should remind you of Java methods. The similarities and differences between them are outlined in Table 1.

Page 10: Oracle SQL Tutorial

Table 1: Functions, procedures and Java methods compared.

Function Procedure Java Method

Parameters input, output input, output input

Returns value yes no optional

Can be called within SQL

PL/SQL Tutorial, Part 2

Need for PL/SQL — declarative vs. procedural — anonymous blocks — debugging — a first program — code compilation — code execution — procedures & functions — PL/SQL in SQL — SQL in PL/SQL — cursors & loops — operators & built-in functions reference tables.

Embedding SQL in PL/SQL

PL/SQL alone does not allow us to query a database, and use the resulting data in our program. However, any SQL (i.e. DML) may be embedded in PL/SQL code. In particular, there exists a form of the ``SELECT'' statement for assigning the result of a

query to a variable. Note the following code requires the books and book_reviews

tables that you should have created during the first Oracle tutorial.

1 CREATE OR REPLACE PROCEDURE count_reviews

2 (author_param VARCHAR2)

3 IS

4 review_count NUMBER;

5 BEGIN

6 SELECT COUNT(*) INTO review_count

7 FROM book_reviews r, books b

Page 11: Oracle SQL Tutorial

8 WHERE b.isbn = r.isbn AND author = author_param;

9

10 IF review_count > 1 THEN

11 dbms_output.put_line('There are '

12 || review_count || ' reviews.');

12 ELSIF review_count = 1 THEN

14 dbms_output.put_line('There is 1 review.');

15 ELSE

16 dbms_output.put_line('There is no review.');

17 END IF;

18 END;

19 /

Note in the code above how:

the procedure takes one parameter author_param of type VARCHAR2 a value from an SQL query is assigned to a PL/SQL variable (i.e. review_count)

using SELECT...INTO... (line 6) a value from a PL/SQL variable is used in an SQL statement (line 8)

Try the programs with different authors:

EXEC count_reviews('Oscar Wilde')

EXEC count_reviews('Charles Dickens')

Working with Cursors

The last program we are going to write will display the number of reviews relevant to each author. Notice that the query may now return multiple rows. However, a SELECT...INTO... statement can only retrieve data from (at most) one  tuple into individual variables. Cursors3 provide a means to retrieve multiple rows into a buffer (when you OPEN the cursor) that can then be traversed sequentially (FETCH) to retrieve individual rows—until there is no more data (cur_revs%NOTFOUND becomes true).

CREATE OR REPLACE PROCEDURE count_by_author

Page 12: Oracle SQL Tutorial

IS

auth VARCHAR2(30);

cnt NUMBER;

CURSOR cur_revs IS

SELECT author, COUNT(author) AS revs_cnt

FROM books b, book_reviews r

WHERE b.isbn = r.isbn GROUP BY author;

BEGIN

OPEN cur_revs;

LOOP

FETCH cur_revs INTO auth, cnt;

EXIT WHEN cur_revs%NOTFOUND;

IF cnt = 1 THEN dbms_output.put_line('1 review for '

|| auth);

ELSE

dbms_output.put_line(cnt || ' reviews for ' || auth);

END IF;

END LOOP;

CLOSE CUR_REVS;

END;

/

Execute count_by_author, adding more data to the tables if necessary.

Page 13: Oracle SQL Tutorial

Table 2: PL/SQL operators.

Operator Description

+ - / * arithmetic

= equality

!= or <> inequality

|| string concatenation

:= assignment

Table 3: Some Oracle built-in functions. You are referred to Oracles's documentation (see References section) for specific usage examples.

Function Description

String Functions

upper(s), lower(s) convert string s to upper/lower-case

initcap(s) capitalise first letter of each word

ltrim(s), rtrim(s) remove blank char. from left/right

substr(s,start,len) sub-string of length len from position start

length(s) length of s

Date Functions

sysdate current date (on Oracle server)

to_date(date, format) date formatting

Number Functions

round(x) round real number x to integer

mod(n,p) n modulus p

abs(x) absolute value of x

dbms_random.random() generate a random integer

Type Conversion Functions

to_char() convert to string

to_date() convert to date

to_number() convert to number

Page 14: Oracle SQL Tutorial

Miscellaneous Functions

user current Oracle user

References

You can copy & paste the following URI (note that you will need a username/password to access Oracle's web site. You can use [email protected]/database):

PL/SQL User's Guide and Reference:

http://download-west.oracle.com/docs/cd/A91202_01/901_doc/appdev.901/a89856/toc.htm

Data Dictionary Tutorial

Data dictionary — metadata — system & object privileges — dictionary structure — ``user'' tables - ``all'' tables — ``dba'' tables — ``v$'' tables — frequently used tables — usage examples — exercises — using the dictionary in PL/SQL programs — optional exercise.

Introduction

This document presents Oracle's data dictionary, also called the system catalogue. The data dictionary is the repository of all the meta-data relevant to the objects stored in the database—and also of information concerning the DBMS itself.

Dictionary Content

Defining metadata.

The term metadata is often defined as data about data. That is, data that provides information about the tables, views, constraints, stored procedures, etc. stored within the database. If we take a table as an example, the dictionary will store information such as:

its name when it was created and when it was last accessed the names and data types of its attributes (i.e. structural information) its owner, who may read and write to it (i.e. security information) where the data is stored (i.e. physical information)

Security in Oracle.

Page 15: Oracle SQL Tutorial

Oracle defines two categories of privileges: object privileges and system privileges. Both categories are granted and revoked using the GRANT and REVOKE SQL constructs:

GRANT <object_privilege> ON <object> TO <user> and GRANT <system_privilege> TO <user>. You have already used the former (see

Introduction to Oracle.) System privileges mainly specify the types of objects a user is allowed to manipulate (tables,...) and what (s)he can do with them. Object privileges define the access rights at the objects level (and even at the attribute level for tables).

Dictionary Structure

The data dictionary is implemented in Oracle as a set of read-only tables and views.

Figure 1: Hierachical structure of the data dictionary.

Figure 1 presents the two-level structure of the dictionary. At the root of the tree is the dictionary table, that features two attributes: table_name and comments. The comment field presents an informal description of the corresponding dictionary table. For instance, we can request information about the dictionary table:

SQL> SELECT comments

Page 16: Oracle SQL Tutorial

2 FROM dictionary WHERE table_name='DICTIONARY'

3 /

and get:

Description of data dictionary tables and views

As an exercise, write a query to find out how many tables make up the data dictionary.

The second level of the dictionary is divided into four categories of tables. ``User'' tables describe the objects you own. They are only accessible to you. ``All'' tables describe the objects of all the users, and are accessible to all the users. ``DBA'' tables contain information only relevant and accessible to database administrators. And last, ``V$'' tables reflect the internal state of the DBMS and are mainly useful to DBAs for performance audit and optimisation. You should refer to Figure 1 for a list of commonly-used dictionary tables. Also, remember that you can obtain the schema of any table with the desc command1 (see Introduction to Oracle)

Introduction to Oracle & Java

JDBC overview — “thin” driver — OCI driver — connecting to Oracle — a generic database access class — insert, update and select examples — exercises.

Introduction

The Java DataBase Connectivity API is a set of classes allowing a straightforward and vendor-neutral access to database management systems. We will review the basic features of JDBC and their use with Oracle

JDBC Overview

Accessibility.

JDBC provides a set of high-level classes that enable anyone acquainted with SQL and Java to write database applications. Considerations like networking and database protocols are transparent to the application programmer. These are handled by classes within JDBC drivers.

Consistency of access across database servers.

To achieve this, JDBC specifications are agreed upon within the Java community--and each database vendor is then left to implement these specification to work with their product.

Page 17: Oracle SQL Tutorial

Thin & OCI Drivers

Oracle provides two main types of drivers.

The OCI driver.

The OCI (type 2) driver consists of java wrappers to the low-level Oracle Call Interface (OCI) libraries used by utilities like SQL*Plus to access the database server. The OCI driver offers potentially better performance that the thin driver. It however requires the OCI libraries to be installed on the local machine.

The ``thin'' driver.

Also referred to as type 4 driver, the thin driver is a pure Java implementation of Oracle's networking protocol (Net8). Being self-contained, it may be used on any machine with--or without Oracle installed--or even distributed with application classes in an applet.

Connecting to Oracle

We will review below how to access Oracle using both types of driver. First, we use the thin driver to connect to Oracle and execute an update statement. Note that the example below is only intended as an illustration. Try to understand the code. You will have opportunities for ``hands-on'' practice in the next section.

import java.io.*;import java.sql.*;

public class OraThin { public static void main(String[] args) { try { Connection con=null; Class.forName("oracle.jdbc.driver.OracleDriver"); con=DriverManager.getConnection( "jdbc:oracle:thin:@machine_name:1521:database_name", "scott", "tiger"); Statement s=con.createStatement(); s.execute(" INSERT INTO BOOKS VALUES ( 'A Tale of Two Cities', 'William Shakespeare', 4567891231, '5-JAN-1962' ) ");

Page 18: Oracle SQL Tutorial

s.close(); con.close(); } catch(Exception e){e.printStackTrace();} }}

The package java.sql containing the JDBC classes is imported. The class OracleDriver, in the package oracle.jdbc.driver is

dynamically loaded into the Java runtime using Class.forName(...). A connection is requested to the database corresponding to the connection URL

with the statement DriverManager.getConnection(...). scott/tiger is an Oracle user/password. We use instances of the Connection and Statement classes to perform a

database operation. The resources hold by these are released using their close() method.

If we want use the OCI driver, the JDBC connection URL above needs to be altered. The only element now required is the service name of the database: database_name. The remainder is resolved using the local Oracle configuration file.

DriverManager.getConnection( "jdbc:oracle:oci8:@database_name", "scott","tiger");

A Generic Database Access Class

In this section we present the DbObject class that allows to connect to an Oracle

database, and execute SQL statements. You will need to download the file DbObjectClasses.jar into your home area and run the command (in UNIX or in a DOS box):

jar xvf DbObjectClasses.jar

This will extract the following files from the archive:

DbObject.java and DbObject.class, the java source and class for our database access class

DbObject.conf, the configuration file of DbObject DbTest.java and DbTest.class, the java source and class file for the test

class DbTest.

Next you need to edit, change and save DbObject.conf so that:

DbObject.User=<your user name> and DbObject.Password=<your Oracle

Page 19: Oracle SQL Tutorial

password>. By default the thin driver is used. You may want to experiment with the

OCI driver by changing DbObject.DriverType to oci8.

You should now run DbTest using the command:

java DbTestThe programme will perform INSERT, UPDATE and SELECT statements. You should

now read carefully both java source files.

Exercises

1. Write a DbTest2 class that inserts data in the book_reviews table. 2. Write a DbTest3 class that displays the number of reviews for each book.

References

You can copy & paste the following URIs (note that you will need a username/password to access Oracle's web site. You can use [email protected]/database):

JavaDoc documentation for the java.sql package: http://java.sun.com/j2se/1.3/docs/api/java/sql/package-summary.html

General JDBC reference: Bruce Eckel. Thinking in Java, Prentice Hall, 2nd. ed., 2000, chap. 15. downloadable from: http://w2.syronex.com/jmr/eckel/

Oracle10i JDBC Developer's Guide and Reference: http://download-west.oracle.com/docs/cd/B10501_01/java.920/a96654/toc.htm

Advanced Oracle & Java

Binary large objects — Java stored procedures — call specifications — triggers.

Introduction

You have been reviewed so far JDBC basics. In the next sections, we will discuss two more advanced topics: how to run PL/SQL code from Java—and conversely, how to run Java code from PL/SQL. The two issues we are going to address during this laboratory have a larger scope than the ones in the previous laboratories.

Java versus PL/SQL.

The considerations listed below outline why and when to use Java rather than PL/SQL:

Page 20: Oracle SQL Tutorial

Java offers more opportunities for reuse accross applications (c.f. class Mod11Ck below)

there are more Java programmers that PL/SQL programmers Java is potentially more efficient for non-database related programmative tasks PL/SQL is a proprietary language only supported by Oracle.

By constrast, PL/SQL has the following advantages:

PL/SQL is tightly integrated with the Oracle DBMS, therefore (argueably) easier to use for database applications

it is more efficient for database-oriented programmative tasks.

BLOBs & Java

Binary Large Objects (BLOBs).

BLOBs are non-atomic, unstructured blocks of binary data stored within a database. We will see in this section how BLOBs can be used to store pictures—and in the next section how Oracle uses BLOBs to store Java classes. As shown below, there exists a BLOB data type in Oracle.

CREATE TABLE pic_store( description VARCHAR2(50), picture BLOB) /

Because of the nature of BLOBs, they own a specific INSERT procedure: an empty

BLOB is first created using the Oracle built-in function empty_blob(). A stream is then

established to the Oracle server to upload the data.

Putting it to work...

The two classes in PicDispClasses.jar display pictures stored as BLOBs in Oracle.

To avoid overloading the database, you will all use the same table pic_store and

account scott/tiger1. Extract the source and class files from the jar archive and

execute the program as follows:

jar xvf PicDispClasses.jar

java PicDisp <picture_description>replacing <picture_description> by one of the values of the description field in

the pic_store table2. Once the code is running, make sure you read and understand

at least the database-related parts of the source code in PicLoader.java.

Java Stored Procedures

Page 21: Oracle SQL Tutorial

We will now write a stored procedure that validates ISBN numbers using the modulo 11 check-digit algorithm (explained in appendix). A trigger (called rules in Postgres) will then be created to apply the check whenever data is inserted to the books table (c.f.

active database concept). The validation procedure we will use only involves numerical computation, but no data-based processing: it is therefore a good candidate to be written in Java. Moreover, the java class once implemented can be reused in other database and non-database related applications. The Mod11Ck Java class below

calculates the check-digit.

public class Mod11Ck { public static String calc(String digStr) { int len = digStr.length(); int sum = 0, rem = 0; int[] digArr = new int[len]; for (int k=1; k<=len; k++) // compute weighted sum sum += (11 - k) * Character.getNumericValue(digStr.charAt(k - 1)); if ((rem = sum % 11) == 0) return "0"; else if (rem == 1) return "X"; else return (new Integer(11 - rem)).toString(); }}

Compile the Java class above and load it into Oracle by issuing the following command:

comp-load-j ./Mod11Ck.java

Note that this is not a standard Oracle utility, but a script that I wrote to read your Oracle username and password from the DbObject.conf file (see Introduction to Oracle & Java.) Be aware that DbObject.conf is expected to be in the current directory. You should be able to lookup the data dictionary to find out whether the Java class compiled successfully (see Oracles's Data Dictionary.) The class will be stored in compiled format as a BLOB, in the database. Next, we need to write a call specification to publish our java (static) method as a PL/SQL function.

CREATE OR REPLACE FUNCTION check_isbn (isbn VARCHAR2) RETURN VARCHAR2AS LANGUAGE JAVANAME 'Mod11Ck.calc(java.lang.String) RETURN java.lang.String';/

We can now write a trigger (c.f. rules in Postgres) that will validate the ISBN for each INSERT statement executed on the books table. If the last digit of the ISBN about to be

Page 22: Oracle SQL Tutorial

inserted does not match the calculated check-digit, an exception is raised—leading the INSERT statement to be rolled-back.

CREATE OR REPLACE TRIGGER check_isbn_on_insBEFORE INSERT ON booksFOR EACH ROW DECLARE new_isbn VARCHAR2(10);BEGIN new_isbn := TO_CHAR(:NEW.isbn); IF NOT (LENGTH(new_isbn) = 10 AND

SUBSTR(new_isbn,10,1) = check_isbn(SUBSTR(new_isbn,1,9))) THEN RAISE_APPLICATION_ERROR(-20000, 'The ISBN number supplied is invalid!'); END IF;END;/

Try to understand how the trigger works.