A JDBC example to show you how to connect to a Oracle database with a JDBC driver.

Tested with:

  • Java 8
  • Oracle database 19c
  • Oracle JDBC driver for Java 8, ojdbc8.jar

1. Download Oracle JDBC Driver

Visit Oracle database website and download the Oracle JDBC Driver.

2. JDBC Connection

Note
Find your Oracle SID in {ORACLE_HOME}/network/admin/tnsnames.ora to avoid the popular ORA-12505, TNS:listener does not currently know of SID

2.1 Make a connection to the Oracle database.

JDBCExample.java

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

public class JDBCExample {

    public static void main(String[] args) {

        // https://docs.oracle.com/javase/8/docs/api/java/sql/package-summary.html#package.description
        // auto java.sql.Driver discovery -- no longer need to load a java.sql.Driver class via Class.forName

        // register JDBC driver, optional since java 1.6
        /*try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }*/

		// Oracle SID = orcl , find yours in tnsname.ora
        try (Connection conn = DriverManager.getConnection(
                "jdbc:oracle:thin:@localhost:1521:orcl", "system", "Password123")) {

            if (conn != null) {
                System.out.println("Connected to the database!");
            } else {
                System.out.println("Failed to make connection!");
            }

        } catch (SQLException e) {
            System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

Compile and run:

C:\test> javac JDBCExample.java

C:\test> java JDBCExample
SQL State: 08001
No suitable driver found for jdbc:oracle:thin:@localhost:1521:orcl

2.2 Assume ojdbc8.jar and JDBCExample.java are stored in c:\test together. Define a -cp option to load everything together:

> java -cp "c:\test\ojdbc8.jar;c:\test" JDBCExample
Connected to the database!

3. Maven Project

3.1 Sorry, due to Oracle license restriction, the Oracle JDBC driver is NOT available in the Maven central repository. Follow this guide to add it – How to add Oracle JDBC driver in your Maven local repository

3.2 Alternatively, defined a system scope to find the .jar file with a specified system path.

pom.xml

	<dependency>
		<groupId>com.oracle</groupId>
		<artifactId>ojdbc</artifactId>
		<version>8</version>
		<scope>system</scope>
		<systemPath>d:/projects/ojdbc8.jar</systemPath>
	</dependency>

Download Source Code

$ git clone https://github.com/favtuts/java-core-tutorials-examples.git

$ cd java-jdbc/oracle

References

Leave a Reply

Your email address will not be published. Required fields are marked *