JDBC & Oracle Basic Example

Total Views : 93
Zoom In Zoom Out Read Later Print

In this post we will create a simple connection to Oracle server using JDBC. We will retrieve all data from a table named users as an test for connection.

JDBC is database-independent connectivity between the Java programming language and databases, but connection URL will be different for different type of databases.

The following code shows how to connect to Oracle and retrieve data from a table.

App.java

import java.sql.*;

public class App {

    private static final String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver";
    private static final String DB_URL = "jdbc:oracle:thin:@localhost:1521:test_db";
    private static final String USER = "root";        // username
    private static final String PASS = "password123"; // password

    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try {
            Class.forName(JDBC_DRIVER);

            conn = DriverManager.getConnection(DB_URL, USER, PASS);

            if (conn != null) {

                System.out.println("Connected");

                stmt = conn.createStatement();

                String sql = "SELECT id, first_name, last_name, age FROM users";
                ResultSet rs = stmt.executeQuery(sql);

                while (rs.next()) {
                    int id = rs.getInt("id");
                    String first_name = rs.getString("first_name");
                    String last_name = rs.getString("last_name");
                    int user_age = rs.getInt("age");

                    System.out.print("ID: " + id);
                    System.out.print(", First Name: " + first_name);
                    System.out.print(", Last Name : " + last_name);
                    System.out.println(", User Age: " + user_age);
                }
                rs.close();
                stmt.close();
                conn.close();

            } else {
                System.out.println("Failed to make connection!");
            }
        } catch (SQLException | ClassNotFoundException se) {
            se.printStackTrace();

        } finally {
            try {
                if (stmt != null)
                    stmt.close();
                if (conn != null)
                    conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
    }
}

Output:

13:14:09: Executing task 'App.main()'...

> Task :compileJava
> Task :processResources NO-SOURCE
> Task :classes

> Task :App.main()
ID: 1, First Name: Manjeet, Last Name : Verma, User Age: 25

BUILD SUCCESSFUL in 1s
2 actionable tasks: 2 executed
13:14:11: Task execution finished 'App.main()'.

See More

Latest Photos