oracledba.help
QuickStarts

Java

<- QuickStarts

Prerequisites

  • Download software.
    • Go to Oracle.com and download the latest Java Development Kit (JDK). Example: jdk-7u45-windows-x64.exe
    • For a Windows system this means selecting i586 or x64 bit version matching your corresponding OS variant.
  • Install the software.
    • Once downloaded run the installation program using the default values. The defaults are optimal for standardizing your installation across all systems.
  • Set the Path environment variable.
    • Under the C:\Program Files\Java directory will be where Java is installed.
      An example would be: C:\Program Files\Java\jdk1.7.0_45
    • Add (don't overwrite the existing value) the following the Java program bin path to your Path environment variable:
      C:\Program Files\Java\jdk1.7.0_45\bin;{other entries}
    • You can test that it is working correctly by entering javac -version at a console window and verifying the screen output
      matches your installed version.
    • The environment can be picky if you have multiple versions of java on this system. A useful trick is to go to any of the .exe files in the Java bin directory right-click the properties, then copy and paste the paste listed for the PATH variable. Pasting it first with a semi colon at the end is the ideal method.
    • Create a working directory for your Java applications.
      A good directory structure for Oracle 11g OFA would be: C:\app\java

Create Test Application

In an editor of your choice create the file hello.java in the C:\app\java directory with the following code:

class hello {
   public static void main (String args[]) {
      System.out.println("Hello World!");
   }
}
  1. Compile the program to a class file by going to a console window and entering the following command:
    javac hello.java
  2. To run the program enter: java hello
    Hello World!

Database Connection Test

Java uses the JDBC to connect to Oracle databases.

Install and Test Java JDBC Driver

  1. Download the jar file ojdbc6.jar from Oracle.
  2. Copy ojdbc6.jar to: C:\Program Files\Java\jdk1.7.0_45/lib
  3. Set the CLASSPATH environment variable.
    Don't remove the old one (if one exists), just add one more to it. Example entry below:
    C:\Program Files\Java\jdk\jdk1.7.0_45\lib\ojdbc6.jar; <== Include the ojdbc6.jar file in the path!
  4. Test that Java can now connect to Oracle.
  5. Create, compile and run the following application (ora_conn.java).
import java.sql.*;
import oracle.jdbc.driver.*;

public class ora_conn {

public static void main(String[] args) {
   // Change these to match your environment. 
   String ServerName = "172.29.12.23";
   String PortNumber = "1521"; String SID = "DB01";
   String ConnString = "jdbc:oracle:thin:@" + ServerName + ":" + PortNumber + ":" + SID;
   String UserName = "scott";
   String Password = "tiger";

   // Load the Oracle JDBC driver 
   try {
      DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());
   } catch (Exception ex) {
      System.err.println(ex.toString());
   }

   try {
	// Load the Oracle JDBC driver Connection 
	Connection conn = DriverManager.getConnection (ConnString, UserName, Password);
	System.out.println("- JDBC driver is installed correctly."); 

	// Create Oracle DatabaseMetaData object and get JDBC Driver Info
	DatabaseMetaData meta = conn.getMetaData();
	System.out.println("- JDBC driver version is " + meta.getDriverVersion());

	// Create a Statement	
	Statement stmt = conn.createStatement();
	System.out.println("- Statement created.");

	// Make a SQL Call
	ResultSet rset = stmt.executeQuery("SELECT sysdate FROM dual");
	System.out.println("- ResultSet created.\n\n");

	// Get Value From Database
	while (rset.next()) {
		System.out.println(rset.getString("SYSDATE") );
	}

	// Close the result set, statement and connection.
	rset.close();
	stmt.close();
	conn.close();	

   } catch(SQLException sqle) {
      System.err.println(sqle);
   }

} // main
} // class

Alternative

Alternatively you can use Oracle's installed Java for local scripts. It is installed under %ORACLE_BASE%\product\{version}\dbhome_1\jdk In this case just make an entry to your PATH statement matching your environment:

 PATH entry: C:\app\oracle\product\11.2.0.3\dbhome_1\jdk\bin;
 OS> javac -version

Then set the CLASSPATH environment variable to the corresponding jdbc driver .jar file. Don't remove the old one (if one exists), just add one more to it. Example entry below (note . entry first):

 .;C:\app\oracle\product\11.2.0.3\dbhome_1\jdbc\lib\ojdbc5.jar;

Batch File To Compile and Run Java App

Place in C:\app\oracle\product\11.2.0.3\dbhome_1\jdk\bin

@echo off
rem File:    j.bat
rem Version: 1.01
cls

echo Compiling %1...
javac %1.java
if "%ERRORLEVEL%" equ "0" GOTO J_RUN

:J_ERROR
goto J_END

:J_RUN
echo Running %1...
echo.
java %1

:J_END
echo.
echo *** Java Program Ended ***
echo.

Java Version In Database

DB Version 11.2 - Java 1.5.0.10
DB Version 11.1 - Java 1.5.0 
DB Version 10.2 - Java 1.4.2 
DB Version 9.2 - Java 1.3.1

Display JDK/JVM Information In Database

Create and run the following java stored procedures in SQLPlus.

connect scott/tiger
create or replace and compile java source named "props" as public class props {
   public static void show_props() {
      System.getProperties().list(System.out);
   }
}
/

show errors

create or replace procedure java_props as language java name 'props.show_props()';
/
show errors

connect / as sysdba
exec dbms_java.grant_permission( 'SCOTT','java.util.PropertyPermission','*','read,write');
commit;

connect scott/tiger
set serveroutput on size 10000
exec dbms_java.set_output(10000)
exec java_props

Example Output

-- listing properties --
oracle.aurora.ncomp.lib.permission=
java.protocol.handler.pkgs=oracle.aurora.rdbms.url
sun.boot.library.path=C:\APP\ORACLE\PRODUCT\11.2.0.3\DBHOME...
java.vm.version=1.5.0_01
oracle.aurora.ncomp.lib.component.prefix=jtc
java.vm.vendor=Oracle Corporation
java.vendor.url=http://www.oracle.com/java/
path.separator=;
java.vm.name=JServer VM
file.encoding.pkg=sun.io
java.vm.specification.name=Java Virtual Machine Specification
user.dir=C:\APP\ORACLE\PRODUCT\11.2.0.3\DBHOME_1
java.awt.graphicsenv=oracle.aurora.awt.OracleGraphicsEnvir...
os.arch=amd64
java.io.tmpdir=C:\Windows\TEMP\
line.separator=
java.vm.specification.vendor=Sun Microsystems Inc.
java.naming.factory.url.pkgs=com.sun.jndi.url
os.name=Windows Server 2008 R2
oracle.aurora.ncomp.file.obj.suffix=obj
java.library.path=c:\app\oracle\product\11.2.0.3\dbhome...
java.specification.name=Java Platform API Specification
java.class.version=48.0
java.net.preferIPv4Stack=FALSE
oracle.aurora.ncomp.file.dll.suffix=dll
java.util.prefs.PreferencesFactory=java.util.prefs.OraclePreferencesFa
os.version=6.1
user.home=
file.encoding=WINDOWS-1252
java.specification.version=1.5
oracle.aurora.ncomp.lib.os.prefix=ora
user.name=
java.class.path=
oracle.aurora.rdbms.SID=DB01db
java.vm.specification.version=1.0
oracle.server.version=11.2.0.3.0
java.home=C:\APP\ORACLE\PRODUCT\11.2.0.3\DBHOME...
java.specification.vendor=Sun Microsystems Inc.
user.language=en
oracle.aurora.rdbms.oracle_home=C:\APP\ORACLE\PRODUCT\11.2.0.3\DBHOME_
awt.toolkit=oracle.aurora.awt.OracleToolkit
oracle.aurora.vm.environment.name=rdbms
java.version=1.5.0_10
java.vendor=Oracle Corporation
java.awt.headless=true
file.separator=\
sqlj.runtime=sqlj.framework.ide.aurora.rdbms.Oracl...
java.compiler=
sun.cpu.endian=little
sun.io.unicode.encoding=UnicodeLittle
oracle.jserver.version=11.0.0.0.0
oracle.aurora.system_subdirectory=bin

PL/SQL procedure successfully completed.

Compile and Run Java (via J.bat) Within Notepad++

-- Create Run Item
Press F6 then paste the below.

NPP_SAVE
cd "$(CURRENT_DIRECTORY)"
"C:\app\oracle\product\11.2.0.3\dbhome_1\jdk\bin\j.bat" $(NAME_PART)

Save as: Java Compile

-- Create NppExec Item

Go to Advance Options within NppExec plugin,
A. Check the box at the top that says "Place to the Macros Submenu"
B. Select script from "Associated Script" combo box. It will automatically fill in the "Item Name".
C. Now click the "Add/Modify" button.
D. Click OK. This will exit the Advanced Options box and say that NotePad++ needs to be restarted.

-- Assign to HotKey

A. Navigate to: Settings -> Shortcut Mapper -> Plugin Commands -> Java Compile
B. Right-Click -> Modify
C. Select Ctrl-F1 (or other combo you desire)

<- QuickStarts