How to connect to Oracle database from java code - JDBC

In this example we are going to connect to the Oracle database.

Pre-requisite:

  1. We need Oracle database up and running.
  2. Oracle JDBC driver
  3. Eclipse IDE (Recommended but not required)
Download oracle jdbc driver from here

If you are working on IDE then create a java project and add the oracle jdbc driver to the build path. And your project structure should look something like this



Now, we are going to write the core logic in order to connect to the oracle database.

package com.amzi.database;

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

public class ConnectOracle {

    public static void main(String[] amzi) {
       
        System.out.println("-------- Oracle JDBC Connection Testing ------");
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
        } catch (ClassNotFoundException e) {
            System.out.println("Oracle JDBC Driver not found!!!");
            e.printStackTrace();
            return;
        }

        System.out.println("Oracle JDBC Driver Registered!");
        Connection connection = null;
        try {
            connection = DriverManager
                    .getConnection(
                            "jdbc:oracle:thin:@localhost:1521:xe",
                            "yourUsername", "yourPassword");
        } catch (SQLException e) {
            System.out.println("Connection Failed!!!");
            e.printStackTrace();
            return;

        }

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


If everything goes fine, you should see your console as below.

-------- Oracle JDBC Connection Testing ------
Oracle JDBC Driver Registered!
Connection established successfully!

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here.
    Kindly keep blogging. If anyone wants to become a Java developer learn from Java EE Online Training from India.
    or learn thru Java EE Online Training from India . Nowadays Java has tons of job opportunities on various vertical industry.

    ReplyDelete