Java Connect to Oracle Database



In this quick tutorial, we show how to connect step by step Java program to the Oracle database server.

In Java, we use a database vendor-specific JDBC driver to connect with that particular database. So, in order to connect the Java program to the Oracle server, we will need to add the Oracle JDBC driver to the classpath.

Steps to connect Java Program to Oracle database

Step 1: Add Oracle JDBC driver

You can download the Oracle JDBC driver from the oracle official website at https://www.oracle.com/database/technologies/appdev/jdbc-downloads.html

Currently there are two main versions of OJDBC:

- OJDBC 8: certified with JDK 8, for Oracle database 11g and 12c.

- OJDBC 10: certified with JDK 10, for Oracle database 18c and 19c.

Extract the downloaded archive, and place the ojdbc10.jar file under your project’s classpath as usual as using any jar file.

If you have a Maven project then add the following dependency to the pom.xml file:

<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc8</artifactId>
    <version>1.0</version>
    <scope>system</scope>
    <systemPath>d:/Path/To/Oracle/JDBC/ojdbc8.jar</systemPath>
</dependency>

Step 2: Configure Oracle Database in Java Program

JDBC URL for Oracle database:
String url = “dbc:oracle:thin:@localhost:1521:demo_db”
Register Driver class:
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
Connect to Oracle database:
String dbURL = "jdbc:oracle:thin:@localhost:1521:demo_db";
String username = "tiger";
String password = "scott";
Connection conn = DriverManager.getConnection(dbURL, username, password);

Complete Program:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
 
public class JdbcOracleConnection {
 
    public static void main(String[] args) {
 
        Connection conn1 = null; 
        try {
            // registers Oracle JDBC driver - though this is no longer required
            // since JDBC 4.0, but added here for backward compatibility
            Class.forName("oracle.jdbc.OracleDriver");
            String dbURL = "jdbc:oracle:thin:@localhost:1521:demo_db";
            String username = "username";
            String password = "password";
            conn1 = DriverManager.getConnection(dbURL, username, password);
            if (conn1 != null) {
                System.out.println("Connected to oracle connection");
            }else{
                System.out.println("Not able to connect to oracle database");
            }
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (SQLException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (conn1 != null && !conn1.isClosed()) {
                    conn1.close();
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }
}

Comments