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
57 Comment threads
15 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
62 Comment authors
PoojaPavanmkyongKeithLeon 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!

trackback
Connect to Oracle DB via JDBC driver – Java

[…] Connection connection = null; connection = DriverManager.getConnection(… [full post] mkyong Mkyong Dot Com javajdbcoracle 0 0 0 0 0 […]

salmon
Guest
salmon

Hi yong,
earlier i have seen lot many java programs under java miscellaneous. now i am unable to find where they are. plz shere me the link of those programs location.

Thanks,
Salmon

Rainer
Guest
Rainer

Thanks for sharing! Easy to use!

Rainer

trackback
JDBC Tutorials

[…] Connect to Oracle DB via JDBC driver Here’s an example to show you how to connect to Oracle database via JDBC driver. […]

ali akbar azizkhani
Guest
ali akbar azizkhani

Class.forName(“org.postgresql.Driver”);

wrong wrong wrong wrong

Kunal
Guest
Kunal

Thanks for this. I really like your blog, it helps me with all my java questions!

Keep on posting!

Saini
Guest
Saini

Thanks for sharing this. How can I measure the time elapsed for establishing the connection? When I use your script, sometimes it comes right back saying all good and sometimes it takes from 20-60 seconds or more.
Thanks.

srinivasa reddy
Guest
srinivasa reddy

Class.forName(“org.postgresql.Driver”);

mr.yong can u change it to Class.forName(“oracle.jdbc.driver.OracleDriver”);

hajer
Guest
hajer

commant fait le connection de java avec oracle

adil
Guest
adil

very nice mykong in the above example
connection = DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:mkyong”, username”,”password”);
what is mykong after the port number is t the database or the service please reply me…

kazi hunk
Guest
kazi hunk
 Oracle JDBC Connection Testing ------
Oracle JDBC Driver Registered!
Connection Failed! Check output console
java.sql.SQLException: Listener refused the connection with the following error:
ORA-12505, TNS:listener does not currently know of SID given in connect descriptor
The Connection descriptor used by the client was:
localhost:1521:hunk

	at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:145)
	at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:380)
	at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:401)
	at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:441)
	at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:165)
	at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:35)
	at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:839)
	at java.sql.DriverManager.getConnection(DriverManager.java:582)
	at java.sql.DriverManager.getConnection(DriverManager.java:185)
	at com.theopentutorials.jdb.oracle.Jdbcconnection.main(Jdbcconnection.java:31)
 
 XML here 
CMFL
Guest
CMFL

Hello, not sure if this answers the question you are having or if this has already been answered but this might help others. It appears that the format for the connection string is now different for newer versions of Oracle. I have tested that this works on 11.X of Oracle.

So instead of this

connection = DriverManager.getConnection(
					"jdbc:oracle:thin:@localhost:1521:mkyong", "username",
					"password");

Try… This instead. Note the ‘/’ at the end instead of the ‘:’

connection = DriverManager.getConnection(
					"jdbc:oracle:thin:@localhost:1521/mkyong", "username",
					"password");
kazi hunk
Guest
kazi hunk

pre lang=”language”>

  im getting this error in eclipse whn irun plz help soon 
Oracle JDBC Connection Testing ------
Oracle JDBC Driver Registered!
Connection Failed! Check output console
java.sql.SQLException: Listener refused the connection with the following error:
ORA-12505, TNS:listener does not currently know of SID given in connect descriptor
The Connection descriptor used by the client was:
localhost:1521:hunk

	at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:145)
	at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:380)
	at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:401)
	at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:441)
	at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:165)
	at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:35)
	at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:839)
	at java.sql.DriverManager.getConnection(DriverManager.java:582)
	at java.sql.DriverManager.getConnection(DriverManager.java:185)
	at com.theopentutorials.jdb.oracle.Jdbcconnection.main(Jdbcconnection.java:31)
 
 XML here 
sivasankar
Guest
sivasankar

Wish u a Happy New Year for mkyong and all the java programmers in this blog .i like this code for jdbc connection

Bill S.
Guest
Bill S.

I think you should use the oracle class instead of the postgresql class.

Change this:

Class.forName("org.postgresql.Driver");

to this:

Class.forName("oracle.jdbc.driver.OracleDriver");
Gooty
Guest
Gooty

hi Java gurus

ARUNKUMAR
Guest
ARUNKUMAR

please tell me the sollution what is the problem !! what am doing in this error ? reply me !!!!! D:\JAVA>javac simple.java D:\JAVA>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(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:164) at OracleJDBC.main(simple.java:13)

Murugan
Guest
Murugan

same problem am getting

sean
Guest
sean

Where is your Oracle JDBC Driver?

Your project needs to reference this file. Right click the project name, and find properties, in there find something like External Libraries, or JARs.
Good luck.

sean
Guest
sean

sry, it needs to reference the ojdbc.jar file.. google for that and download it from oracle. its the libraries of classes you’re using, such as Connection, Statement, DriverManager.

sean
Guest
sean

also guys… its awkward that you ask this, when its the first thing in the instructions:

#1. Download Oracle JDBC Driver
Get Oracle JDBC driver here – ojdbcxxx.jar

he even gives you a link. scroll to the Top of the page you’re reading this on.

azhar
Guest
azhar

i got error got minus one form a read call
jdk 1.6 oracle 10.2.0.1.0 ojdbc6.jar

Ankur
Guest
Ankur

liked ur code for jdbc connection test

obaid
Guest
obaid

is there anyone..who knows the solution for this problem..
actly i m trying to connect jdbc with oracle..
..
but i m unable to run this..
i m getting this msg
C:\Users\OBAID\workspace\checking\src\org>java check
Exception in thread “main” java.lang.UnsupportedClassVersionError: check (Unsupp
orted major.minor version 51.0)
at java.lang.ClassLoader.defineClass0(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(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.ClassLoader.loadClassInternal(Unknown Source)

C:\Users\OBAID\workspace\checking\src\org>

Brent Vermilion
Guest
Brent Vermilion

Perfect! Thank you.

Rajesh
Guest
Rajesh

it’s working ..Thank u pal….

jake
Guest
jake

hello,

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

udyan
Guest
udyan

Thanks a lot ….

akshat
Guest
akshat

how to connect java to oracle 10g with netbeans ?

azmath
Guest
azmath

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

please reply as soon as possible
thank you

Suresh M Sidy
Guest
Suresh M Sidy

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

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.

Featured Posts