Enter your keyword

post

Get Oracle DB connection using Oracle driver

Here is an example to connect Oracle DB using Oracle driver.

1) Download Oracle JDBC Driver

Download Oracle JDBC Driver from  here

2) set classpath of the above jar

3) Use below code to connect Oracle DB

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

public class ObtainDBConnection {
    public ObtainDBConnection() {
        super();
    }

    private static Connection getConnnection() {

        try {
            // Load oracle driver
            Class.forName(“oracle.jdbc.driver.OracleDriver”);
           
        } catch (ClassNotFoundException e) {

            System.out.println(“Oracle JDBC Driver not found”);
            e.printStackTrace();
            return null;

        }

        Connection connection = null;

        try {
           
            String connectionString = “jdbc:oracle:thin:@localhost:1521:orcl”;
            String userName = “hr”;
            String password = “welcome1”;

            connection =
                    DriverManager.getConnection(connectionString,userName, password);

        } catch (SQLException e) {

            System.out.println(“Oracle database connection couldn’t be established. Please check DB details!!”);
            e.printStackTrace();
            return null;

        }

        if (connection != null) {
            System.out.println(“DB connection established successfully”);
            return connection;
        } else {
            System.out.println(“Failed to connect DB.”);
            return null;
        }
    }
   
    public static void main(String args[]){
        Connection connection = ObtainDBConnection.getConnnection();
       
        System.out.println(“Connection “+connection);
       
    }
}

Leave a Reply

Your email address will not be published.