Pages Navigation Menu

Coding is much easier than you think

Connect to Oracle DB via JDBC driver

Connect to Oracle DB via JDBC driver

 
Here is an example to show you how to connect to Oracle database via JDBC driver.
 
 1. Download Oracle JDBC Driver
 
Get Oracle JDBC driver here – ojdbcxxx.jar
 
2. Java JDBC connection example
 
Code snippets to use JDBC to connect a Oracle database.
 
** UPDATE: Complete JDBC tutorial now available here.
 

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection = null;
connection = DriverManager.getConnection(
	"jdbc:oracle:thin:@hostname:port:dbname","username","password");
connection.close();

 
See a complete example below:
File: OracleJDBC.java
 

package com.simplecode.jdbc;

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

public class OracleJDBC {
	
private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver";
private static final String DB_CONNECTION="jdbc:oracle:thin:@localhost:1521:SIMPLECODEDB";
private static final String DB_USER = "username";
private static final String DB_PASSWORD = "password";

public static void main(String[] argc) {

	System.out.println("**** Oracle JDBC Driver Connection Establishing ****");

	try 
	{
	Class.forName(DB_DRIVER);
	} 
        catch (ClassNotFoundException e) 
	{
		System.out.println("Exception : Add Oracle JDBC Driver in your classpath ");
		System.err.println(e.getMessage());
		return;
	}

	System.out.println("*Oracle JDBC Driver Registered!");
	Connection connection = null;

	try 
	{
	connection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
	}
	catch (SQLException e) {

		System.out.println("Connection Failed!);
		System.err.println(e.getMessage());
		return;
	}

	if (connection == null) {
		System.out.println("Connection Failed!");
	} 
	else 
	{
		System.out.println("Connection established!");

	}
}
}

 

About Mohaideen Jamil


Am currently working as a Struts 2 Developer in a reputed IT Organisations. I can help you with teaching Core java and Struts 2. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.