How do I connect to Oracle using JDBC?

To connect to an Oracle database using JDBC, you’ll need the Oracle JDBC driver (typically ojdbc8.jar or later) and a connection string formatted as a Thin URL.

Here is the step-by-step process and a code example.

1. Add the Dependency

If you are using Maven, add the ojdbc dependency to your pom.xml. For Java 11+, ojdbc8 or ojdbc11 is recommended.

<dependency>
    <groupId>com.oracle.database.jdbc</groupId>
    <artifactId>ojdbc8</artifactId>
    <version>21.1.0.0</version>
</dependency>

2. Connection Details

The standard Oracle Thin URL format is:
jdbc:oracle:thin:@<host>:<port>:<SID> or jdbc:oracle:thin:@<host>:<port>/<service_name>

  • Host: The server address (e.g., localhost).
  • Port: Usually 1521.
  • SID/Service Name: The specific database instance name (e.g., xe or orcl).

3. Java Example

We can use a try-with-resources block to ensure the connection is closed automatically.

package org.kodejava.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class OracleConnectionExample {
    public static void main(String[] args) {
        // Oracle connection URL
        // Format: jdbc:oracle:thin:@hostname:port:SID
        String url = "jdbc:oracle:thin:@localhost:1521:xe";
        String username = "your_username";
        String password = "your_password";

        try (Connection connection = DriverManager.getConnection(url, username, password)) {
            if (connection != null) {
                System.out.println("Connected to the Oracle database!");

                // You can perform database operations here

            }
        } catch (SQLException e) {
            System.err.println("Connection failed!");
            e.printStackTrace();
        }
    }
}

Key Points to Remember:

  • Driver Loading: In modern JDBC (4.0+), you don’t need to call Class.forName("oracle.jdbc.driver.OracleDriver") manually; the DriverManager will find it automatically if the JAR is on your classpath.
  • Thin vs. OCI: The “Thin” driver is a pure Java driver that doesn’t require Oracle client software installed on the machine, making it the most common choice for applications.
  • Service Names: If you are connecting to an Oracle 12c or newer (pluggable databases), you usually use the slash / syntax for the service name instead of the colon : for the SID.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.