Using Oracle and JDBC on NJIT AFS and Prophet systems

41
1 NJIT JDBC/Oracle tutorial Using Oracle on NJIT Computers by George Blank, Yong Hong Wu, Luv Tulsidas, and Bijal Desai

Transcript of Using Oracle and JDBC on NJIT AFS and Prophet systems

Page 1: Using Oracle and JDBC on NJIT AFS and Prophet systems

1

NJIT

JDBC/Oracle tutorial

Using Oracle on NJIT Computers

by George Blank, Yong Hong Wu, Luv Tulsidas, and Bijal Desai

Page 2: Using Oracle and JDBC on NJIT AFS and Prophet systems

2

Topics covered

Resources Setup Oracle environment on NJIT Install Oracle JDBC driver Introduction to Oracle 9 Oracle SQL*Plus Basics Introduction to JDBC JDBC Basics A sample JDBC program Summary References

Page 3: Using Oracle and JDBC on NJIT AFS and Prophet systems

3

Before Installation

You cannot connect to Prophet using JDBC unless you do it from AFS. This is for security.

You must use the version of Java installed on AFS and the JDBC drivers in the [ORACLE_HOME]/jdbc directory.

You use the Oracle Thin Driver (not the OCI Driver). This is an all Java driver.

Every time Oracle or the JDK is upgraded, there may be some changes to this document.

Page 4: Using Oracle and JDBC on NJIT AFS and Prophet systems

4

Accessing Oracle 10g at NJIT

If you have an AFS account and are registered for this class, you should automatically have a Prophet account with Oracle at NJIT.

Access prophet using Aqua Data Studio. See information at http://web.njit.edu/info/limpid/Oracle_on_prophet_njit_edu.html#ADS You should have received your username and password in the email already.

Use 'course' as Connection Identifier. If you don't have username and password, contact (

[email protected]) For help, go to http://web.njit.edu/ and select Databases

from the menu on the left.

Page 5: Using Oracle and JDBC on NJIT AFS and Prophet systems

5

Accessing University Computing Systems

You can get to UCS using SSH You can use any system from afs1 to afs36

See http://web.njit.edu/~gblank/Help.ppt for information on SSH and http://csd.njit.edu/accounts/afs.phpfor information on UCS.

Page 6: Using Oracle and JDBC on NJIT AFS and Prophet systems

6

Testing JDBC

Using your Prophet username and password, login to one of the afsnn computers to enter, compile and execute the Java program on the next four slides.

Page 7: Using Oracle and JDBC on NJIT AFS and Prophet systems

7

Test Program (1)***************Test.java*****************

import java.sql.*;

class Test{public static void main (String args [])throws SQLException{// Load the Oracle JDBC driverDriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

Page 8: Using Oracle and JDBC on NJIT AFS and Prophet systems

8

Test Program (2)String url = "jdbc:oracle:thin:@prophet.njit.edu:1521:course";

try {String url1 = System.getProperty("JDBC_URL");if (url1 != null)url = url1;} catch (Exception e) {// If there is any security exception, ignore it// and use the default}

Page 9: Using Oracle and JDBC on NJIT AFS and Prophet systems

9

Test Program (3)// Connect to the databaseConnection conn = DriverManager.getConnection (url,"username","password");

// Create a StatementStatement stmt = conn.createStatement ();

// Select the SYSDATE column from the dual tableResultSet rset = stmt.executeQuery ("select SYSDATE from dual");

Page 10: Using Oracle and JDBC on NJIT AFS and Prophet systems

10

Test Program (4)// Print the resultwhile (rset.next ())System.out.println (rset.getString (1));

// Close the ResultSetrset.close();

// Close the Statementstmt.close();

// Close the connectionconn.close();}}

Page 11: Using Oracle and JDBC on NJIT AFS and Prophet systems

11

Execute Test Program Save the file and exit, i.e. if using pico type CTRL

X and press yes. Compile the java code by typing the following at

the command prompt: javac test.java Once the program is successfully compiled,

execute it by typing:java test

The program will identify whether or not the connection to Oracle was successful.

Page 12: Using Oracle and JDBC on NJIT AFS and Prophet systems

12

Errors

If the program reports that your connection to oracle was unsuccessful or you receive java exceptions, it may be a problem specific to your AFS account.

Page 13: Using Oracle and JDBC on NJIT AFS and Prophet systems

13

Introduction to Oracle

Oracle is an Object Relational Database Management System(ORDBMS).

It offers capabilities of both relational and object-oriented database systems.

Page 14: Using Oracle and JDBC on NJIT AFS and Prophet systems

14

Tools of Oracle

The tools provided by Oracle are so user friendly that a person with minimum skills in the field of computers can access them with ease.The main tools are: -SQL *Plus

-PL/SQL-Forms-Reports

Page 15: Using Oracle and JDBC on NJIT AFS and Prophet systems

15

Introduction to SQL

SQL was invented and developed by IBM in early 1970’s. SQL stands for Structured Query Language.

Oracle’s database Language is SQL, which is used for storing and retrieving information in Oracle.

A table is a primary database object of SQL that is used to store data.

Page 16: Using Oracle and JDBC on NJIT AFS and Prophet systems

16

Introduction to SQL(Cont’d)

In order to communicate with the database, SQL supports the following categories of commands:-

Data Definition Language- create, alter,drop commands.

Data Manipulation Language- insert, select, delete and update commands.

Transaction Control Language- commit, savepoint and rollback commands.

Data Control Language- grant and revoke commands.

Page 17: Using Oracle and JDBC on NJIT AFS and Prophet systems

17

Benefits of SQL

Non-procedural language, because more than one record can be accessed rather than one record at a time.

It is common language for all relational databases. In other words it is portable and it requires very few modifications so that it can work on other databases.

Very simple commands for querying, inserting and modifying data and objects.

Page 18: Using Oracle and JDBC on NJIT AFS and Prophet systems

18

SQL*Plus

SQL*Plus is an Oracle specific program which accepts SQL commands and PL/SQL blocks and executes them. SQL*Plus enables manipulation of SQL commands and PL/SQL blocks. It performs many additional tasks as well.

Page 19: Using Oracle and JDBC on NJIT AFS and Prophet systems

19

Oracle Basics

You must have an existing database instance before you can create an oracle relation (table).

If you use NJIT Oracle account, you are already given a database instance when DBA opens the account for you.

Note that the following discussion is generic, and not specific to NJIT’s Prophet account.

Page 20: Using Oracle and JDBC on NJIT AFS and Prophet systems

20

Oracle Internal Datatypes Character datatypes:

- char datatype- varchar2 datatype- Long datatype

Number datatype Date datatype Raw datatype Long raw datatype LOB datatype

Page 21: Using Oracle and JDBC on NJIT AFS and Prophet systems

21

Data Definition Language Create tables

SQL> CREATE TABLE <table_name> ( <column1_name> <data_type> <[not]null>,

<column2_name> <data_type> <[not]null>, . . . . CONSTRAINT pk_name PRIMARY KEY (column_name);

CONSTRAINT fk_name FOREIGN KEY (column_name)); REFERENCE name1(name2) ON DELETE CASCADE);

Alter the existing table SQL> ALTER TABLE <table_name> MODIFY/ADD (column definition);

Page 22: Using Oracle and JDBC on NJIT AFS and Prophet systems

22

Data Definition Language(Cont’d)

When there is no further use of records in a table and the structure has to be retained, then the records alone can be deleted. SQL>TRUNCATE table <table_name>;

Drop a tableSQL>DROP <table_name>;

Page 23: Using Oracle and JDBC on NJIT AFS and Prophet systems

23

Data manipulation Language

Insert a tuple into a table SQL>INSERT <table_name> VALUES ( value_1, value_2, value_3 ..); Request for information stored in a table SQL> SELECT column_names FROM table_name;

Change the existing records in the table SQL>UPDATE <table_name> SET <field>=value,….. WHERE condition;

Delete the rows in the table SQL>DELETE FROM <table_name> WHERE condition;

Page 24: Using Oracle and JDBC on NJIT AFS and Prophet systems

24

Transaction Control Language

Transaction Changes can be made permanent to a database only by committing. Commit command is used to end a transaction and make the changes permanent.

SQL>COMMIT; Savepoints are like markers to divide a very

lengthy transaction to smaller ones.

SQL> SAVEPOINT savepoint_id;

Page 25: Using Oracle and JDBC on NJIT AFS and Prophet systems

25

Transaction Control Language(Cont’d)

Rollback command is used to undo the work done in the current transaction.

SQL> ROLLBACK ; SQL> ROLLBACK TO SAVEPOINT savepoint_id;

Page 26: Using Oracle and JDBC on NJIT AFS and Prophet systems

26

Data Control language

Grant privilege command: Object privileges can be granted to others using the SQL command GRANT

SQL>GRANT privileges on<object_name> to <username>;

To withdraw the privilege that has been granted to a user, we use REVOKE command.

SQL>REVOKE privileges on<object_name> from <username>;

Page 27: Using Oracle and JDBC on NJIT AFS and Prophet systems

27

Introduction to JDBC

What is JDBC ?JDBC is a Java API for executing SQL

statements. It consists of a set of classes and interfaces written in Java programming language. JDBC provides a standard API for tool/database developers and makes it possible to write database applications using pure Java API.

Page 28: Using Oracle and JDBC on NJIT AFS and Prophet systems

28

What Does JDBC Do ?

JDBC makes it possible to do three things: Establish a connection with a database Send SQL statements Process the results.

Page 29: Using Oracle and JDBC on NJIT AFS and Prophet systems

29

JDBC Driver Types

The JDBC Drivers that we are aware of at this time fit into one of four categories: 1) JDBC-ODBC bridge plus ODBC driver2)Native-API partly_Java driver3)JDBC-Net pure Java driver4)Native-protocol pure Java driver

Categories 3 and 4 are the preferred way to access databases from JDBC.

Page 30: Using Oracle and JDBC on NJIT AFS and Prophet systems

30

JDBC Basics

First you need to establish a connection with Oracle database. This involves two steps: (1) load the driver (2) make the connection. To load the driver: for NJIT Oracle account:

DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

Page 31: Using Oracle and JDBC on NJIT AFS and Prophet systems

31

JDBC Basics (cont’d)

Make a connection to have the appropriate driver connect to Oracle by calling Connection Con = DriverManager.getConnection(url,“userID”, “password”);

This method returns an open connection you can use to create JDBC statements that pass your SQL statements to the Oracle. For NJIT Oracle accountString url ="jdbc:oracle:thin:@prophet.njit.edu:1521:course”

Page 32: Using Oracle and JDBC on NJIT AFS and Prophet systems

32

JDBC Basics (cont’d)

The second step is to create a Statement object to send SQL statement to Oracle. It takes an instance of an active connection to create a Statement object. A Statement has two methods, executeUpdate() and excuteQuery().Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery(query_name); stmt.executeUpdate(DDL_statement);

ExcuteQuery() executes a prepared SQL statement and returns the result set in a ResultSet object.

Page 33: Using Oracle and JDBC on NJIT AFS and Prophet systems

33

JDBC Basics (cont’d)

ExecuteUpdate() is used for updates and DLL statements only. Nothing should be returned for executeUpdate() method. A SQL exception will be thrown if executeUpdate() returns anything, or executeQuery() returns nothing.

The third step is to create an instance of ResultSet to hold query results, as show below. ResultSet rs = stmt.executeQuery(query_name);

ResultSet has several useful methods:

Page 34: Using Oracle and JDBC on NJIT AFS and Prophet systems

34

JDBC Basics (cont’d)

next() method works like a pointer moving from the beginning of the result set towards the end. Each time it is invoked, the next row becomes the current row

getXXX() method, where XXX is data type, retrieves the value in each column of the result set.

The following code accessed the values in the current row of ResultSet rs and prints out the coffee name and price.

String query = "select COF_NAME, PRICE from COFFEES"; ResultSet rs = stmt.executeQuery(query);

Page 35: Using Oracle and JDBC on NJIT AFS and Prophet systems

35

JDBC Basics (cont’d)

while (rs.next()) { String s = rs.getString(”Coffee Name");

Float f = rs.getFloat("Price"); System.out.println(s + " " + f);

} Using Prepared Statements Prepared Statement object contains a

precomplied SQL statement, and it cost less excution time than Statement object.

String query = “Update Customer set Phone = ? Where CID = ?”;

Page 36: Using Oracle and JDBC on NJIT AFS and Prophet systems

36

JDBC Basics (cont’d)

PreparedStatement updatePhone = con.prepareStatement(query);

UpdatePhone.setString(1, ‘991-5668’); UpdatePhone.setInt(2, 4567); UpdatePhone.excuteUpdate();

The above code will change the phone number for the customer whose ID is ‘4567’. SetXXX() method takes two arguments, the first one indicates which question mark is to be set, the second one supplies value to it. After the setXXX() method, the SQL statement is equivalent toquery = “Update Customer set Phone = ‘991-5668’ Where CID = 4567”;

Page 37: Using Oracle and JDBC on NJIT AFS and Prophet systems

37

Summary

JDBC makes it very easy to connect to DBMS and to manipulate the data in it.

You have to install the oracle driver in order to make the connection.

It is crucial to setup PATH and CLASSPATH properly

Page 38: Using Oracle and JDBC on NJIT AFS and Prophet systems

38

Very Important Make certain you close your connection:

con.close(); If you end your program, but do not specifically close

the connection, Oracle keeps a connection open. In April of 2002, Oracle had to be shut down and restarted due to hundreds of abandoned opened connections.

In the corporate world, creating a problem that caused the database to be shut down would result in disciplinary action.

The Database log tells who left the connection open.

Page 39: Using Oracle and JDBC on NJIT AFS and Prophet systems

39

Problems Encountered

What causes the "No suitable driver" error?

"No suitable driver" is an error that usually occurs during a call to the DriverManager.getConnection method. The cause can be failing to load the appropriate JDBC drivers before calling the getConnection method, or it can be specifying an invalid JDBC URL--one that isn't recognized by your JDBC driver. Your best bet is to check the documentation for your JDBC driver or contact your JDBC driver vendor if you suspect that the URL you are specifying is not being recognized by your JDBC driver.

Page 40: Using Oracle and JDBC on NJIT AFS and Prophet systems

40

Problems Encountered

What causes the "No suitable driver" error? (continued) Do not install or upgrade drivers in your AFS account or modify your .profile or .login files in an attempt to get JDBC to work. It is very strictly configured to work with only the particular version of the thin driver and Prophet. Students who tried upgrading the drivers or modifying their profiles have been totally unable to connect.

Page 41: Using Oracle and JDBC on NJIT AFS and Prophet systems

41

References

White,Seth and Maydene Fisher.1999. JDBC API Tutorial and Reference, 2nd Ed. Addison-Wesley

Graham Hamilton,Rick Cattell, Maydene Fisher. JDBC Database Access With Java, A Tutorial and Annotated Reference

Holowczak, Richard. ORACLE SQL*PLUS:An Introduction and tutorial. At www.cimic.rutgers.edu/~holowcaz/oracle/sqlplus.

Instructions for Prophet can be found at: http://web.njit.edu/ under Databases on the menu