Java JDBC Connection to Oracle Database Example

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

Learn a complete JDBC tutorial at https://www.javaguides.net/p/jdbc-tutorial.html.

JDBC Connection to Oracle Database Example

Download the Ojdbc8.jar file and add it to the classpath of your project.
For the maven project, use below maven dependency:
<!-- https://mvnrepository.com/artifact/com.oracle.jdbc/ojdbc8 --> <dependency> <groupId>com.oracle.jdbc</groupId> <artifactId>ojdbc8</artifactId> <version>12.2.0.1</version> </dependency>

Here is the JDBC example to connect to an Oracle database with a JDBC driver:

import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class JDBCExample { public static void main(String[] args) { // 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(); } } }

Output:
Connected to the database!

References


Comments