Performing join on the two tables - Java program

Q. Write a program to combine data from more than one table in Java.

Answer:

Below example performs join operation on two table. The two tables are “Emp” and “Dept”.

The join operation works on the basis of common column between both table. The dept_id is the common between these two table.

Following are the steps to create this application.

1. Create “Emp” table

Create table emp (emp_id number, empname varchar2(10), email varchar2(30), city varchar2(10), dept_id number);

2. Create “Dept” table

Create table emp (dept_id number, department varchar2(10));

3. Develop the Java Application

JoinExample.java

import java.sql.*;
class JoinExample
{
     public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:XE";
     public static final String DBUSER = "local";
     public static final String DBPASS = "test";
     public static void main(String args[])
     {
          try
          {
               //Load the driver
               Class.forName("oracle.jdbc.driver.OracleDriver");
               //Create the connection object
               Connection con = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
               //Query String
               String sql = "select empname, city, department from emp e inner join dept d on e.dept_id = d.dept_id";
               Statement stmt = con.createStatement();
               ResultSet result = stmt.executeQuery(sql);
               System.out.println("EmpName  City   Department");
               System.out.println("**===========**==========**");
               while (result.next())
               {
                    System.out.println (
                         result.getString(1)+"   "+
                         result.getString(2)+"     "+
                         result.getString(3));
               }
               System.out.println("**===========**==========**\n");
          }
          catch(Exception ex)
          {
               ex.printStackTrace();
          }
     }
}


Output:

join