Connect to Oracle DB via JDBC driver

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.

Oracle JDBC driver
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

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
55 Comment threads
15 Thread replies
1 Followers
 
Most reacted comment
Hottest comment thread
60 Comment authors
KeithLeonNadeemRameshAndrew Recent comment authors
newest oldest most voted
Felipe Windmoller
Guest
Felipe Windmoller

Hello Mkyong!

First I had the “ORA-12505, TNS:listener does not currently know of SID given in connect descriptor” problem.
Then I replaced the “xe” by the correct “service name” that was in the tnsnames.ora

Thanks for the example, it worked fine for me!

Rajesh
Guest
Rajesh

I am getting following error:
C:\oracle\product>java -cp C:\oracle\product\11.2.0\client_1\jdbc\lib\ojdbc6.jar;C:\oracle\product\11.2.0\client_1\jdbc\lib oraclejdbc
Error: Could not find or load main class oraclejdbc
plz explain in detail

Ho Quoc Tri
Guest
Ho Quoc Tri

Very simple and easy to understand!

Thank you!

Andrew
Guest
Andrew

thanks

BurakO
Guest
BurakO

Very easy and success!
Thank you.

Haris
Guest
Haris

Hi Mkyong

Can you please guide me how to use TNSNAMES.ORA file Java JDBC Connection example above?

Regards
-Haris

gumuruh s
Guest
gumuruh s

i’m having a question for this code….

if we want to connect to Oracle 11g database,
from what you just wrote on the code above,…

it says : “org.postgresql.Driver” -> why we wrote postgresql instead of Oracle 11g?

Miroslav Kovarik
Guest
Miroslav Kovarik

Very useful. Thank you! Simple, working, clear.

Harshagiri
Guest
Harshagiri

If we create multiple instance of the connection class which includes same URL, Username and password. When we close the connection, will all connections created using same username and password will also be closed?

JW
Guest
JW

Wow – I’m impressed that noone before me found out that in the complete example there is no closing of the connection using the connection.close(); as described in the first example…
Four years….

Rana Zahid
Guest
Rana Zahid

Thank’s a lot. I have done it.

rtanwar
Guest
rtanwar

Thanks for easy to imbibe page.

Please guide,

is it possible to create a persistent Database connection and use it for all database access for all sessions in web application as separate connection may cause exhausting number of processes in oracle.

Akshita
Guest
Akshita

How can we specify the address of Jdbc
my jdbc is located in oracle
please give me reply

edward iceden
Guest
edward iceden

thanks it worked !

here is is my output

run:

——– Oracle JDBC Connection Testing ——

Oracle JDBC Driver Registered!

You made it, take control your database now!

BUILD SUCCESSFUL (total time: 0 seconds)

rame
Guest
rame

hi, above code was useful to get connection. thanks

DucQuoc.wordpress.com
Guest
DucQuoc.wordpress.com

Thanks, it’s very nice tutor.

But why using “PostgreSQL” driver for Oracle connection?

>>
Class.forName(“org.postgresql.Driver”);
//…
>>

mkyong
Guest
mkyong

Sorry, typo, fixed.

om kesarwani
Guest
om kesarwani

i’m trying to connect oracle database by ojdbc14.jar where should i save it and how to run this..;;
bcause i’m finding a error that is claasnotfound..

pls help me..

chand
Guest
chand

right click on computer and go to properties and go to advanced system settings and go to environment variables and click on new
and variable name classpath and in variable path E:oracleproduct10.2.0db_1jdbclibojdbc14.jar;
then prss ok its connected to database

Menios
Guest
Menios

Nice simple post for quick reference!

Sriram
Guest
Sriram

Thanks a tonnnne Mr.Mkyong. I never thought oracle odbc connectivity would be this simple.. Thanks again..:-)

Ooga
Guest
Ooga

That’s JDBC, not ODBC. I know, “OJDBC” confuses me some times also :)

iRun26pt2
Guest
iRun26pt2

Thank You! I was looking for something simple to get me going and this did it!

krishna
Guest
krishna

1)where i can find driver classname–

i.e, oracle.jdbc.driver.OracleDriver
2)where i can get url

iam waiting for ur reply

trackback
java get table list and package arguments from oracle | :: uisp :: dsin ::

[…] ref : java2s, mkyong […]

David Wallace
Guest
David Wallace

Did you mean to reference org.postgresql.Driver in the very first snippet?

Sarveshwar Prasad
Guest
Sarveshwar Prasad

C:\Users\Sarveshwar\Desktop>javac OracleJDBC.java C:\Users\Sarveshwar\Desktop>java OracleJDBC ——– Oracle JDBC Connection Testing —— Where is your Oracle JDBC Driver? java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver at java.net.URLClassLoader$1.run(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Unknown Source) at OracleJDBC.main(OracleJDBC.java:13) JDBC is present in Oracle(11g) or Java? please specify the address of JDBC.

Suresh M Sidy
Guest
Suresh M Sidy

may i have the link of ‘any software/flat form for Java editor along with JDBC connector?

azmath
Guest
azmath

when i try your first command
i am getting an error – access denied

please reply as soon as possible
thank you

akshat
Guest
akshat

how to connect java to oracle 10g with netbeans ?

udyan
Guest
udyan

Thanks a lot ….

jake
Guest
jake

hello,

how can i implement a class so that other classes can use it for database connection?
thanks you

Rajesh
Guest
Rajesh

it’s working ..Thank u pal….