Connecting to Oracle Database in Java

This article is a step by step guide on connecting to an Oracle database from a Java program. The following standalone program demonstrates Oracle database connectivity using JDBC API. In this program we will use the Oracle’s built dummy table DUAL to retrieve Oracle’s system date.

Java provides a standard interface to connect to databases and it is known as JDBC (Java Database Connectivity). Oracle provides an implementation library of this JDBC interface using which Java programs can connect to a running oracle database instance.

Step 1 : Download Oracle JDBC Drivers

You can download Oracle JDBC drivers from here. Choose the version appropriate for your database version. In this example, I use the Oracle 11g JDBC driver since I connect to Oracle 11g database. There are two versions available for Oracle 11g, ojdbc5.jar (for JDK 1.5) and ojdbc6.jar (for JDK 1.6). Use appropriate version for your Java installation (Oracle now requires online registration for downloading drivers). I use ojdbc6.jar for this tutorial.

Step 2 : Java Program to Connect to Oracle

The following Java program uses Oracle JDBC driver to connect to a running Oracle database instance. You can use this program on any Oracle database as this example uses Oracle’s built-in dummy table DUAL for fetching system date. DUAL enables us to get values such as system date using a normal SQL query.

// Example Java Program - Oracle Database Connectivity
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class OracleSample {

    public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:XE";
    public static final String DBUSER = "system";
    public static final String DBPASS = "manager";

    public static void main(String[] args) throws SQLException {
        
        // Load Oracle JDBC Driver
        DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
        
        // Connect to Oracle Database
        Connection con = DriverManager.getConnection(DBURL, DBUSER, DBPASS);

        Statement statement = con.createStatement();

        // Execute a SELECT query on Oracle Dummy DUAL Table. Useful for retrieving system values
        // Enables us to retrieve values as if querying from a table
        ResultSet rs = statement.executeQuery("SELECT SYSDATE FROM DUAL");
        
        
        if (rs.next()) {
            Date currentDate = rs.getDate(1); // get first column returned
            System.out.println("Current Date from Oracle is : "+currentDate);
        }
        rs.close();
        statement.close();
        con.close();
    }
}

Before you run the program ensure that you change the values for DBURL, DBUSER and DBPASS. DBURL is of the form,

jdbc:oracle:thin:@machinename:1521:databasename

Replace machinename with the name of the machine where oracle is running and replace databasename with service name of the database instance.

See this page for more details on JDBC API.

Step 3 : Add ojdbc.jar to Classpath

In order to compile or run the above program, you need to add ojdbc.jar to the classpath of your program. If you are using IDE such as NetBeans or Eclipse, you can add ojdbc.jar as a dependent library and NetBeans will automatically add it to classpath.

If you are running the above program from command line, copy ojdbc.jar to the folder where the above Java program is located and then compile the file using the following command (this adds ojdbc.jar to classpath),

javac -classpath ./ojdbc6.jar OracleSample.java

Run the Java program using the following command (ojdbc.jar is added to classpath),

java -classpath "./ojdbc6.jar;." OracleSample

Note that when you are running OracleSample, you need both the JDCB jar file and the current folder in the classpath. If everything went well, you will see the following output.

Connecting to Oracle database using Java - Example

If you don’t have an oracle instance for testing this program, you can download the free Oracle 11g Express edition from here.

Base64 String Encoding in Java

Base64 is encoding scheme that can represent binary data in ASCII string format. This is useful whenever arbitrary data needs to be passed across systems as textual data. This ensures that binary data which may have special meaning to the transport layer remains intact during transport. Encoding and storing image binary data as an XML text node is a typical usage scenario.

Original Text: This is a test string   Encoded String: VGhpcyBpcyBhIHRlc3Qgc3RyaW5n

The following Java program generates a base64 encoded string for an input string. This example uses sun.misc.BASE which is part of the Java SDK but is not officially supported by Oracle.

Base64 Encoding Example in Java

// Base64 encoding in Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import sun.misc.BASE64Encoder;

public class Base64Encoder {

    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Please enter a string to encode : ");
        String source = reader.readLine();
        
        BASE64Encoder encoder = new BASE64Encoder();
        System.out.println("Encoded string is : "+encoder.encode(source.getBytes()));
    }
    
}

Another option is to use the commons codec library which I would recommend for production systems.

Find Largest Number in an Array Using Java

The following Java program finds the largest number in a given array. Initially the largest variable value is set as the smallest integer value (Integer.MIN_VALUE) and whenever a bigger number is found in array, it is overwritten with the new value. We iterate through the entire array with the above logic to find the largest number.

Print the Largest Number in an Array Using Java

// Java program to find largest number in an array
public class FindLargest {
    
    public static void main(String[] args) {
        int[] numbers = {88,33,55,23,64,123};
        int largest = Integer.MIN_VALUE;
        
        for(int i =0;i<numbers.length;i++) {
            if(numbers[i] > largest) {
                largest = numbers[i];
            }
        }
        
        System.out.println("Largest number in array is : " +largest);
    }
}

Java Program to Print All Alphabets

The following Java program prints all alphabets in English language. This program uses the Java character variable and built-in ordering of the character variable values. The following program prints both capital letters and small letters.

Write a Java Program to Print All English Alphabets

// Java program to print all english alphabets
public class AllAlphabets {
    public static void main(String[] args) {
        System.out.print("Capital alphabets in english are : ");
        for(char c='A'; c<='Z';c++) {
            System.out.print(c+",");
        }
        System.out.println();
        
        System.out.print("Small alphabets in english are : ");
        for(char c='a'; c<='z';c++) {
            System.out.print(c+",");
        }
        System.out.println();
    }
}

Java Program to Find Area of a Circle

The formula for finding area of a circle is,

area = PI * radius * radius

Where PI is a constant (approximately 3.1416) and radius is the radius of the circle.

Calculate Area of a Circle in Java

The following Java program calculates the area of a circle given the radius of the circle. This program demonstrates a number of key concepts in Java programming,

  • How to obtain user input from console
  • How to write output to console
  • How to use IO classes and decorator pattern
  • Using library classes such as Math, BufferedReader, Double etc.
  • Performing mathematical calculations
// Java program to calculate area of a circle
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class CircleArea {
     public static void main(String[] args) throws IOException{
        
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Please enter the radius of the circle : ");
        double radius = Double.parseDouble(reader.readLine());
        
        double area = Math.PI * radius * radius;
        
        System.out.println("Area of the circle with radius "+radius+" is : "+area);
        
    }
}