|
Sometimes user has to fetch the data from the different tables at the same time and on the basis of some conditions. Let us consider there is an employee and Dept table. Employee table has the DeptId as the field but in case we want the name of department then we have to fetch the employee information from the employee table and Dept name is taken out from the dept table on the basis of dept id stored in the Employee table. For joins the two tables should be having some relations.
package com.visualbuilder;
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement;
public class JoinExample {
public static void main(String[] args) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); /** Getting Connection*/ Connection con = DriverManager.getConnection System.out.println("Connection estalished"); /** Creating Statement*/ Statement stmt = con.createStatement(); /** Creating simple table*/ ResultSetrs=stmt.executeQuery("select emp.ename,dept.dname from emp, dept where dept.deptno =emp.deptno and emp.ename like 'A%'"); while(rs.next()) { System.out.print("Name of the employee is " rs.getString("ename")); System.out.println(" Dept name is " rs.getString("dname")); } /** Closing the Connection*/ stmt.close(); con.close(); } catch (Exception e) { e.printStackTrace();
}
} }
Output:-
Connection estalished
Name of the employee is Adam Dept name is Sales
Name of the employee is Adran Dept name is Marketing |