How to Connect Oracle Database in Java Using NetBeans?

  • Java
  • 2 mins read

Here is an example to demonstrate how to connect Oracle Database in Java using NetBeans. The difference in any Java program to run without NetBeans or with NetBeans is, in Java you need to specify the classpath to run the program and in NetBeans, you need to add the JAR file to the project. Follow these steps:

Connect Oracle Database in Java Using NetBeans

  1. Download the Oracle JDBC driver (ojdbc7.jar) from Oracle.com
  2. Learn how to add a JAR file to the NetBeans Project
  3. After completing the above two steps, you would be able to connect to the Oracle Database. The following is the example Java program:
//ConnectOracle.java

import java.sql.*;

class ConnectOracle {

    public static void main(String args[]) {
        try {

    // Load the JDBC Driver
            Class.forName("oracle.jdbc.driver.OracleDriver");

// Create a connection
            Connection con = DriverManager.getConnection(
                    "jdbc:oracle:thin:@localhost:1521:orcl", "scott", "tiger");

// Create a statement for SQL query
            Statement stmt = con.createStatement();

// Execute the query
            ResultSet rs = stmt.executeQuery("select sysdate from dual");
            while (rs.next()) {
                System.out.println("Oracle Database current date is " + rs.getString(1));
            }

// Close the connection object  
            con.close();

        } catch (Exception e) {
            System.out.println(e);
        }

    }
}

Output

run:
Oracle Database current date is 2019-03-20 14:47:01.0
BUILD SUCCESSFUL (total time: 1 second)

Below is the example of running the above Java program without using NetBeans. The f:\orajars\ is the location of ojdbc7.jar file and f:\NetBeansProjects\Java1\src is the location of your project.

java -cp f:\orajars\ojdbc7.jar;f:\NetBeansProjects\Java1\src ConnectOracle

Output

Oracle Database current date is 2019-03-20 14:52:03.0

See also: