2017  Kodetalk | Feedback | Privacy Policy | Terms | About

how to connect with oracle database using java api?

how to connect with oracle database using java api?

The following Java program uses Oracle JDBC driver to connect to a running Oracle database instance. You can use this program on any Oracle database as this example uses Oracle’s built-in dummy table DUAL for fetching system date. DUAL enables us to get values such as system date using a normal SQL query.

// Example Java Program - Oracle Database Connectivity
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class OracleSample {

    public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:XE";
    public static final String DBUSER = "system";
    public static final String DBPASS = "manager";

    public static void main(String[] args) throws SQLException {
        // Load Oracle JDBC Driver
        DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
        // Connect to Oracle Database
        Connection con = DriverManager.getConnection(DBURL, DBUSER, DBPASS);

        Statement statement = con.createStatement();

        // Execute a SELECT query on Oracle Dummy DUAL Table. Useful for retrieving system values
        // Enables us to retrieve values as if querying from a table
        ResultSet rs = statement.executeQuery("SELECT SYSDATE FROM DUAL");
        if (rs.next()) {
            Date currentDate = rs.getDate(1); // get first column returned
            System.out.println("Current Date from Oracle is : "+currentDate);

Before you run the program ensure that you change the values for DBURL, DBUSER and DBPASS. DBURL is of the form, and You can download Oracle JDBC drivers from here.

Answer is