Connect to Oracle DB via JDBC driver – Java

Oracle JDBC example in Java.

Download Oracle JDBC
Get Oracle JDBC driver here – ojdbcxxx.jar
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection = null;
connection = DriverManager.getConnection(
	"jdbc:oracle:thin:@localhost:1521:ziben","username","password");
connection.close();
See a full example to show you how to connect to Oracle database via Oracle JDBC driver in Java.

File : OracleJDBC.java

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
 
public class OracleJDBC {
 
	public static void main(String[] argv) {
 
		System.out.println("-------- Oracle JDBC Connection Testing ------------");
 
		try {
 			Class.forName("oracle.jdbc.driver.OracleDriver");
 		} catch (ClassNotFoundException e) {
 			System.out.println("Where is your Oracle JDBC Driver?");
			e.printStackTrace();
			return;
		}
 		System.out.println("Oracle JDBC Driver Registered!");
 
		Connection connection = null;
 
		try {
			connection = DriverManager.getConnection(
			    "jdbc:oracle:thin:@localhost:1521:ziben","username","password");
 
		} catch (SQLException e) {
 
			System.out.println("Connection Failed! Check output console");
			e.printStackTrace();
			return;
 		}
 
		if (connection != null){
			System.out.println("You made it, take control your database now!");
		}else{
			System.out.println("Failed to make connection!");
		}
	}
}

How to run it?

Assume OracleJDBC.java is store in “/home/ziben/jdbc-test” folder, together with Oracle JDBC driver (ojdbc6.jar), then run following commands :

/home/ziben/jdbc-test$ javac OracleJDBC.java
 
/home/ziben/jdbc-test$ java -cp /home/ziben/jdbc-test/jdbc-test/ojdbc6.jar;/home/ziben/jdbc-test/jdbc-test OracleJDBC
-------- Oracle JDBC Connection Testing ------------
Oracle JDBC Driver Registered!
You made it, take control your database now!
 
/home/ziben/jdbc-test$

Published by

Claudio Cardozo

Ubuntu Kernel Team Membership, Certified SCRUM Master, System Architect, Open Source enthusiastic, Java and JavaFX passioned, OpenCRX Team, Theologist, minimalist lifestyle, eitaa!

Leave a Reply