Wednesday 3 July 2013

Connect To Oracle DB Via JDBC Driver

// siddhu vydyabhushana // 2 comments
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.
Class.forName("org.postgresql.Driver");
Connection connection = null;
connection = DriverManager.getConnection(
 "jdbc:oracle:thin:@localhost:1521:mkyong","username","password");
connection.close();
See a complete example below :
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:mkyong", "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!");
  }
 }
 
}

2. Run it

Assume OracleJDBC.java is store in “C:\jdbc-test” folder, together with Oracle JDBC driver (ojdbc6.jar), then run following commands :
C:\jdbc-test>javac OracleJDBC.java
 
C:\jdbc-test>java -cp c:\jdbc-test\ojdbc6.jar;c:\jdbc-test OracleJDBC
-------- Oracle JDBC Connection Testing ------------
Oracle JDBC Driver Registered!
You made it, take control your database now!
 
C:\jdbc-test>
Done.

2 comments:

  1. Really it was an awesome article...very interesting to read..You have provided an nice article....Thanks for sharing.

    Best BCA Colleges in Noida

    ReplyDelete
  2. Really it was an awesome article...very interesting to read..You have provided an nice article....Thanks for sharing.

    Best BCA Colleges in Noida

    ReplyDelete