* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Download JDBC/Oracle tutorial
Relational algebra wikipedia , lookup
Tandem Computers wikipedia , lookup
Microsoft Access wikipedia , lookup
Concurrency control wikipedia , lookup
Entity–attribute–value model wikipedia , lookup
Ingres (database) wikipedia , lookup
Extensible Storage Engine wikipedia , lookup
Microsoft Jet Database Engine wikipedia , lookup
Clusterpoint wikipedia , lookup
Microsoft SQL Server wikipedia , lookup
Database model wikipedia , lookup
Relational model wikipedia , lookup
Oracle Database wikipedia , lookup
JDBC/Oracle tutorial
Using Oracle
on NJIT Computers
NJIT
1
by George Blank, Yong Hong Wu,
Luv Tulsidas, and Bijal Desai
Topics covered
2
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
Before Installation
3
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.
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
4
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
(sys@oak.njit.edu)
For help, go to http://web.njit.edu/ and select Databases
from the menu on the left.
Accessing University
Computing Systems
5
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.php
for information on UCS.
Testing JDBC
6
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.
Test Program (1)
***************Test.java*****************
import java.sql.*;
class Test
{
public static void main (String args [])
throws SQLException
{
// Load the Oracle JDBC driver
DriverManager.registerDriver(new
oracle.jdbc.driver.OracleDriver());
7
Test Program (2)
String url =
"jdbc:oracle:thin:@prophet.njit.edu:1521:cours
e";
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
}
8
Test Program (3)
// Connect to the database
Connection conn = DriverManager.getConnection
(url,"username","password");
// Create a Statement
Statement stmt = conn.createStatement ();
// Select the SYSDATE column from the dual
table
ResultSet rset = stmt.executeQuery ("select
SYSDATE from dual");
9
Test Program (4)
// Print the result
while (rset.next ())
System.out.println (rset.getString (1));
// Close the ResultSet
rset.close();
// Close the Statement
stmt.close();
// Close the connection
conn.close();
}
10 }
Execute Test Program
11
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.
Errors
12
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.
Introduction to Oracle
Oracle is an Object Relational Database
Management System(ORDBMS).
It offers capabilities of both relational and objectoriented database systems.
13
Tools of Oracle
14
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
Introduction to SQL
15
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.
Introduction to SQL(Cont’d)
16
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.
Benefits of SQL
17
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.
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.
18
Oracle Basics
19
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.
Oracle Internal Datatypes
20
Character datatypes:
- char datatype
- varchar2 datatype
- Long datatype
Number datatype
Date datatype
Raw datatype
Long raw datatype
LOB datatype
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);
21
Alter the existing table
SQL> ALTER TABLE <table_name> MODIFY/ADD (column
definition);
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 table
SQL>DROP <table_name>;
22
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;
23
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;
24
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;
25
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>;
26
Introduction to JDBC
27
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.
What Does JDBC Do ?
JDBC makes it possible to do three things:
28
Establish a connection with a database
Send SQL statements
Process the results.
JDBC Driver Types
29
The JDBC Drivers that we are aware of at this
time fit into one of four categories:
1) JDBC-ODBC bridge plus ODBC driver
2)Native-API partly_Java driver
3)JDBC-Net pure Java driver
4)Native-protocol pure Java driver
Categories 3 and 4 are the preferred way to
access databases from JDBC.
JDBC Basics
First you need to establish a connection with
Oracle database. This involves two steps: (1)
load the driver (2) make the connection.
30
To load the driver:
for NJIT Oracle account:
DriverManager.registerDriver(new
oracle.jdbc.driver.OracleDriver());
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 account
String url
="jdbc:oracle:thin:@prophet.njit.edu:1521:course”
31
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.
32
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);
33
ResultSet has several useful methods:
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);
34
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 = ?”;
35
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 to
query = “Update Customer set Phone = ‘991-5668’
Where CID = 4567”;
36
Summary
37
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
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.
38
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.
39
Problems Encountered
40
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.
References
41
White,Seth and Maydene Fisher.1999. JDBC
API Tutorial and Reference, 2nd Ed. AddisonWesley
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