Home Tutorial Java Jdbc Natural Join / joining two tables

 
 

Natural Join / joining two tables
Posted on: June 1, 2010 at 12:00 AM
A join provide the facility to merge two tables according to common field and Create a new virtual field. We will use the following query-

Natural Join / joining two tables 

A join provide the facility to merge two tables according to common field and Create a new virtual field. We will use the following query-

SELECT * FROM employee NATURAL JOIN emp_sal 

Here, "NATURAL JOIN"  join the two table according to common field and store it in "Statement " class object.

The two tables before join --

"employee" table

"emp_sal" table

NatJoin.java

import java.sql.*;

public class NatJoin{
public static void main(String[] args) {
System.out.println("Table after Natural Join");
Connection con = null;
try{
  Class.forName("com.mysql.jdbc.Driver");
  con = DriverManager.getConnection("jdbc:mysql://192.168.10.13:3306/ankdb","root","root");
 try{
  Statement st = con.createStatement();
        //Join two tables
 ResultSet res = st.executeQuery("SELECT *FROM "+"employee"+" NATURAL JOIN "+"emp_sal");
        
 System.out.println("Emp_code" + "\t" + "Emp_name" + "\t" + "Emp_salary"+"\t"+"Emp_designation";
 while(res.next()){
 int code = res.getInt("Emp_code");
 String name = res.getString("Emp_name");
 String sal = res.getString("Emp_salary");
 String post = res.getString("Emp_designation");

 System.out.println(code + "\t\t" + name + "\t\t" + sal+"\t\t"+post);
   }
  }
  catch (SQLException s){
   System.out.println("Error in excution of SQL statement");
    }
    }
    catch (Exception e){
   e.printStackTrace();
    }
  }
}

OUTPUT

Download Example's code

Related Tags for Natural Join / joining two tables:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.