How to Display Data from Database in JTable Java Example

Display Data from Database in JTable

In this tutorial, I have written Simple Java Program about, How to Display Data from Database in JTable. The Program were tested with MySQL database and all details were shared in the post.

Environment Details

  • JDK 1.7
  • MySQL Database
  • Eclipse IDE

Table Query

CREATE TABLE employee_details (empId INT, empName VARCHAR(30), empAge INT, empQualification VARCHAR(30), empAddress VARCHAR(50), PRIMARY KEY(empId));

Display Data from Database in JTable

Display Data from Database in JTable

Project Structure

Display Data from Database in JTable

Right Click on Project -> Go to Properties -> Go to Java Build Path -> Press Add Jars Button -> Select the Jar file from Project Lib Folder -> Click Ok

EmployeeDetails.java

package com.dineshkrish.swing;

import java.awt.BorderLayout;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class EmployeeDetails {
	
	private boolean status;

	public EmployeeDetails(String title) {

		// Creating Window using JFrame
		JFrame frame = new JFrame();
		frame.setTitle(title);
		frame.setSize(800, 500);

		// Adding Table View
		frame.add(getTablePanel());

		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}

	private JPanel getTablePanel() {

		JPanel tableJPanel = new JPanel();
		
		tableJPanel.setLayout(new BorderLayout());
		
		// Column Header
		String[] columns = {

		"Ëmployee ID", "Employee Name", "Employee Age",
				"Employee Qualification", "Employee Address" };

		// Getting Data for Table from Database
		Object[][] data = getEmployeeDetails();

		// Creating JTable object passing data and header
		JTable employeeTable = new JTable(data, columns);
		
		
		tableJPanel.add(employeeTable.getTableHeader(), BorderLayout.NORTH);
		tableJPanel.add(employeeTable, BorderLayout.CENTER);
		
		return tableJPanel;
	}

	private Object[][] getEmployeeDetails() {

		Object[][] data = null;

		final String DRIVER_NAME = "com.mysql.jdbc.Driver";
		final String CONNECTION_URL = "jdbc:mysql://localhost:3306/ems";
		final String USERNAME = "root";
		final String PASSWORD = "";

		final String QUERY = "Select empId, empName, empAge, empQualification, empAddress from employee_details";

		try {

			// Loading the Driver
			Class.forName(DRIVER_NAME);

			// Getting Database Connection Object by Passing URL, Username and Password
			Connection connection = DriverManager.getConnection(CONNECTION_URL, USERNAME, PASSWORD);

			Statement statement = connection.createStatement();

			ResultSet rs = statement.executeQuery(QUERY);

			int rowCount = getRowCount(rs); // Row Count
			int columnCount = getColumnCount(rs); // Column Count

			data = new Object[rowCount][columnCount];

			// Starting from First Row for Iteration
			rs.beforeFirst();

			int i = 0;
			
			while (rs.next()) {

				int j = 0;

				data[i][j++] = rs.getInt("empId");
				data[i][j++] = rs.getString("empName");
				data[i][j++] = rs.getInt("empAge");
				data[i][j++] = rs.getString("empQualification");
				data[i][j++] = rs.getString("empAddress");

				i++;
			}

			status = true;
			
			// Closing the Resources;
			statement.close();
			connection.close();
			
		} catch (Exception e) {

			e.printStackTrace();
		}

		return data;
	}

	// Method to get Row Count from ResultSet Object
	private int getRowCount(ResultSet rs) {

		try {
			
			if(rs != null) {
				
				rs.last();
				
				return rs.getRow(); 
			}
			
		} catch (SQLException e) {

			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		
		return 0;
	}

	// Method to get Column Count from ResultSet Object
	private int getColumnCount(ResultSet rs) {

		try {

			if(rs != null)
				return rs.getMetaData().getColumnCount();

		} catch (SQLException e) {

			System.out.println(e.getMessage());
			e.printStackTrace();
		}

		return 0;
	}

	@Override
	public String toString() {
		
		return (status) ? "Data Listed Successfully" : "Application Error Occured";
	}
	
	public static void main(String[] args) {

		String title = "Employee Details Table";

		EmployeeDetails employeeDetails = new EmployeeDetails(title);

		System.out.println(employeeDetails);
	}
}

Output

Data Listed Successfully

Display Data from Database in JTable

References

1. Java SQL Documentation
2. Java Swing API Documentation

Hello, folks, I am a founder of dineshkrish.com. I love Java and Open source technologies, If you find my tutorials are useful, please consider making donations to these charities.