Java Program to Join Contents of More than One Table & Display in JDBC
Last Updated :
09 Jan, 2023
Java supports many databases and for each database, we need to have their respective jar files to be placed in the build path to proceed for JDBC connectivity. First, need to decide, which database we are using and accordingly, we need to add the jars. For other databases like Progress, Cassandra, etc also we have jars and need to include them in the build path. There are different kinds of joins available in MySQL and depends upon the requirement, we can frame queries.
Join is a join that provides the facility to connect two tables are merged with each other according to a field that is common and creates a new virtual table.
- NATURAL JOIN: It is a type of join that retrieves data within specified tables to a specific field that is matched.
- NATURAL LEFT JOIN: In this operation, both tables are merged with each other according to common fields but the priority is given to the first table in the database.
- NATURAL RIGHT JOIN: It also the same as Natural left join but it retrieves the data from the second table in the database.
MySQL tables that are used in code:
First table
CREATE TABLE `studentsdetails` (
`id` int(6) unsigned NOT NULL,
`Name` varchar(50) NOT NULL,
`caste` varchar(10) NOT NULL,
`NeetMarks` int(11) NOT NULL,
`gender` varchar(10) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Second table
CREATE TABLE `studentspersonaldetails` (
`id` int(6) unsigned NOT NULL AUTO_INCREMENT,
`Name` varchar(30) NOT NULL,
`Address` varchar(30) NOT NULL,
`email` varchar(50) DEFAULT NULL,
`reg_date` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;

In both tables, “Name” is the common column. 1st table specifies Gender, NeetMarks, Caste, etc whereas 2nd table specifies the address, email, etc. Now only necessity is to create an SQL query to join the table which is as follows:
SELECT * FROM " + "studentsdetails" + " NATURAL JOIN " + "studentspersonaldetails"
Now as this query is executed it retrieves data within specified tables to a specific field is matched, it will match records in both tables depends upon “Name” column, implementing the Natural join concept in play. Now the program depends upon the data present in both tables and for matching values of “Name” column in both tables to get the desired output.
Implementation: Now executing the above query command with the help of the below program as per Natural Join.
Java
import java.sql.*;
public class GFG {
public static void main(String[] args)
{
System.out.println(
"Joining 2 MySQL tables using Natural Join" );
Connection con = null ;
try {
Class.forName( "com.mysql.cj.jdbc.Driver" );
con = DriverManager.getConnection(
"root" , "" );
try {
Statement st = con.createStatement();
ResultSet res = st.executeQuery(
"SELECT *FROM "
+ "studentsdetails"
+ " NATURAL JOIN "
+ "studentspersonaldetails" );
System.out.println( " StuName"
+ " Gender"
+ " Caste "
+ "Neet Marks"
+ " Email" );
while (res.next()) {
String name = res.getString( "Name" );
String gender = res.getString( "gender" );
String caste = res.getString( "caste" );
String neetMarks
= res.getString( "NeetMarks" );
String email = res.getString( "email" );
System.out.format(
"%10s%10s%10s%10s%20s\n" , name,
gender, caste, neetMarks, email);
}
con.close();
}
catch (SQLException s) {
System.out.println(
"SQL statement is not executed!" );
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
|
Output :

Similarly, we can use the rest of the other joins too in the SQL query. Join and Natural join alone makes columns matching in both tables and display data from both tables. As per the requirements, for
- Natural left join: Priority goes to the first table.
- Natural right join: Priority goes to the second table.
For different servers, there are different jar files used.
For SQL
Step 1: Load the driver class
jar to be used: sqljdbc4.jar
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Step 2: Create a connection for which the connection string “HOSP_SQL1.company.com” is a user-defined one. Similarly, we can use username, password, the database can be used as shown
Connection conn = DriverManager.getConnection(“jdbc:sqlserver://HOSP_SQL1.company.com;user=name;password=abcdefg;database=Test”);
For Oracle
Step 1: Load the driver class
jar to be used: ojdbc14.jar
Class.forName("oracle.jdbc.driver.OracleDriver");
Step 2: Create a connection object followed by username and password
Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
Similar Reads
Java Program to Search the Contents of a Table in JDBC
In order to deal with JDBC standard 7 steps are supposed to be followed: Import the databaseLoad and register driversCreate a connectionCreate a statementExecute the queryProcess the resultsClose the connectionProcedure: Import the database-syntax for importing the sql database in java is- import ja
5 min read
How to Sort Contents of a Table in JDBC?
Sorting the contents of a table means rearranging the records in an organized way to make data more usable. You can sort all the records of a table by choosing a column within a table according to which data has to be sorted. In simple words, when you sort data, you arrange the data in a logical ord
4 min read
Java Program to Delete a Column in a Table Using JDBC
Before deleting a column in a table, first is need to connect the java application to the database. Java has its own API which JDBC API which uses JDBC drivers for database connections. Before JDBC, ODBC API was used but it was written in C which means it was platform-dependent. JDBC API provides th
3 min read
Java Program to Use Methods of Column to Get Column Name in JDBC
Java Database Connectivity or JDBC is a Java API (application programming interface) used to perform database operations through Java application. It allows the execution of SQL commands for the creation of tables and data manipulation through Java application. Java supports java.sql package which c
4 min read
Java Program to Insert Details in a Table using JDBC
Java Database Connectivity is basically a standard API(application interface) between the java programming language and various databases like Oracle, SQL, Postgres, SQL, etc. It connects the front end(for interacting with the users ) with the backend( for storing data). Algorithm: Search/ Insert/ D
4 min read
Java Program to Implement Control Table in Java
Control tables will be tables that control the control stream or have a significant influence on program control. There are no unbending guidelines about the structure or substance of a control tableâits passing trait is its capacity to coordinate the control stream somehow or another through "execu
3 min read
How to Use Different Row Methods to Get Number of Rows in a Table in JDBC?
Java supports many databases and for each database, we need to have their respective jar files to be placed in the build path to proceed for JDBC connectivity. For different databases, different jar files are imported to make a connection given below or their built path is supposed to be added for s
5 min read
Java Program to Output Query Results in Tabular Format in JDBC
JDBC (Java Database Connectivity) is a standard API(application interface) between the java programming language and various databases like oracle,SQL, etc.it connects the front end for interacting with the users with the backend for storing data. Procedure: Creating a databaseConnection classOutput
5 min read
Implementation of Materialized view through the Java Program
Prerequisites: JDBC, SQL views. A view is simply any SELECT query that has been given a name and saved in the database. For this reason, a view is sometimes called a named query or a stored query. Materialized views are the views which are similar to the normal views except one property that they ar
5 min read
Java JDBC Programs - Basic to Advanced
This article provides a variety of programs on JDBC, that are frequently asked in the technical round in various Software Engineering/JAVA Backend Developer Interviews including various operations such as CREATE, INSERT, UPDATE, DELETE and SELECT on SQL Database etc. Additionally, all programs come
3 min read