Hello Friends, Welcome to my new tutorial and in this tutorial, we will learn how to retrieve data from database and display it in JTable using Java Swing with simple and easy steps. A Java JTable is a class that is used to display data in the form of rows and columns.
In my previous tutorial, we learned how to install MySQL Workbench on Windows, Mac, and Ubuntu Operating System, and Now we will learn how to fetch data from the database and populate it in JTable.
I have used Eclipse IDE in this tutorial for the program development, but You can use any IDE like NetBeans or Intellij IDEA because the programming logic will be the same.
For the database, I have used MySQL Workbench, which is nothing but a GUI version of the MySQL console, where we can visually design, model, and generates databases.
I have also given the program’s source code at the end of this tutorial from where you can download it.
So let’s start our tutorial on how to retrieve data from database and display it in JTable using Java Swing.
How to Retrieve Data From Database and Display it in JTable Using Java Swing
First of all, I want to summarize what I am going to do in this tutorial. I am going to create a database in the back-end with a table in it named student and In the front end, I will set up the GUI, and when I will input the name of the student and click on the “Fetch Data” button, the table should show up with the details of that particular student.
How to Install MySQL WorkBench Full Tutorial
Creating Database in MySQL Workbench
- open MySQL WorkBench and then go to Database>Connect to Database.
- A pop-up window will be opened just click on ok.
- Once you click on “ok” it will ask you for a password. It is the same password which you have used during the installation process. So enter the correct password and then click on the “ok” button.
- Now create a database (studentDatabse in this example), and inside that database, create a table (student in this example) with the following fields.
- USERNAME
- ROLLNO
- DEPARTMENT
1 2 3 4 |
create database studentDatabase; use studentDatabase; create table student(USERNAME varchar(30) not null, ROLLNO varchar(10), DEPARTMENT varchar(30)); |
- Now insert some values into it.
1 2 |
insert into student values('Mehtab','1','Cse'); insert into student values('Jack','2','Phy'); |
Setting Up the GUI
- The next thing you have to do is set up the GUI to add the components to it.
- Go to Eclipse IDE and create a new Java Project.
- For this, you click on the Java Project under the new section of File Menu (File>>New>>Java Project).
- Now give a name to your project (FetchDataExample in this example) and click on “Finish”.
- Now right click on the project and create a new Java class (New>>Class).
- Now give a name to your class(FetchData in this Example), tick mark on the public static void main(String[] args), and then click on the Finish button as shown in the figure below.
- Now Implement the ActionListener interface to our class so that we will be able to do some button click event in our program. And if we are implementing the ActionListener interface in our class, we have to override it’s method actionPerformed() into our class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class FetchData implements ActionListener { public static void main(String[] args) { } @Override public void actionPerformed(ActionEvent e) { } } |
- Now create the window using the JFrame class of swing, and it’s methods then add components to it.
- The components are,
- one JLabel (username label)
- one JTextField ( For entering the username)
- Two JButtons ( one for fetching data and one for resetting the username text field)
- Below is the code, and I have also explained the code in the comments.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; import java.awt.*; public class FetchData implements ActionListener { JFrame frame1;//creating object of first JFrame JLabel nameLabel;//creating object of JLabel JTextField nameTextField;//creating object of JTextfield JButton fetchButton; //creating object of JButton JButton resetButton;//creating object of JButton FetchData(){ frame1 = new JFrame(); frame1.setTitle("Search Database");//setting the title of first JFrame frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//setting default close operation GridBagLayout bagLayout = new GridBagLayout();//creating object of GridBagLayout GridBagConstraints bagConstraints = new GridBagConstraints();//creating object of GridBagConstratints frame1.setSize(500, 300);//setting the size of first JFrame frame1.setLayout(bagLayout);//setting the layout to GridBagLayout of first JFrame bagConstraints.insets = new Insets(15, 40, 0, 0);//Setting the padding between the components and neighboring components //Setting the property of JLabel and adding it to the first JFrame nameLabel = new JLabel("Enter Username"); bagConstraints.gridx = 0; bagConstraints.gridy = 0; frame1.add(nameLabel, bagConstraints); //Setting the property of JTextfield and adding it to the first JFrame nameTextField = new JTextField(15); bagConstraints.gridx = 1; bagConstraints.gridy = 0; frame1.add(nameTextField, bagConstraints); //Setting the property of JButton(Fetch Data) and adding it to the first JFrame fetchButton = new JButton("Fetch Data"); bagConstraints.gridx = 0; bagConstraints.gridy = 1; bagConstraints.ipadx = 60; frame1.add(fetchButton, bagConstraints); //Setting the property of JButton(Reset Data) and adding it to the second JFrame resetButton = new JButton("Reset Data"); bagConstraints.gridx = 1; bagConstraints.gridy = 1; frame1.add(resetButton, bagConstraints); frame1.setVisible(true);//Setting the visibility of First JFrame frame1.validate();//Performing relayout of the First JFrame } public static void main(String[] args) { new FetchData();//Creating object of class FetchData } @Override public void actionPerformed(ActionEvent e) { } } |
- Now run your program
- As you can see, the window is successfully created, and components are added to it.
Connecting to Database
- In order to connect your Java program with MySQL database, you need to include MySQL JDBC driver which is a JAR file, namely mysql-connector-java-5.1.49-bin.jar. The version number in the Jar file can be different.
- You can download the latest version of MySQL connector from this link (MySQL Connector Java download) As shown in the figure below.
- Extract the zip archive and you will get the jar file.
- Next, you have to include this jar file into your program so that you will be able to connect your java program with MySQL database.
- Right-click on the project, go to the properties section then select Java Build Path and click on the Add External JARs button.
- After clicking on the button a pop-up window will appear where you have to select and open the jar file.
- You can see the added Jar file as shown in the figure below. Now click on the Apply and Close button.
- Now we want that when we enter the username and click on the Fetch data Button, that particular student’s details should show up in a new window inside the JTable. And if we Enter the wrong username and click on the Fetch data button, then the message dialog box should show a specific message.
- If we click on the Reset Button, then it should clear the username text field.
Setting up JTable and Retrieving Data From the Database to JTable
In this section, you will learn how to fetch data from database in Java and display in table, which means we will search and display data from database in Java.
- For this, you need to create objects of,
- A JFrame
- A JTable
- A DefaultTableModel (this is used when no model is specifically defined)
- A Connection object
- A Statement object
- Now when someone enters the username and clicks on the “Fetch Data” button, the student’s details should show up on another JFrame inside the JTable.
- And If we enter the wrong username, then message dialog box should show us the message “No such username found”.
- And If we click on the Reset Button, then username text field should be cleared.
- The Final programming code is given below, and I have also explained the code in the comments.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 |
import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.*; public class FetchData implements ActionListener { JFrame frame1;//creating object of first JFrame JLabel nameLabel;//creating object of JLabel JTextField nameTextField;//creating object of JTextfield JButton fetchButton;//creating object of JButton JButton resetButton;//creating object of JButton JFrame frame2;//creating object of second JFrame DefaultTableModel defaultTableModel;//creating object of DefaultTableModel JTable table;//Creating object of JTable Connection connection;//Creating object of Connection class Statement statement;//Creating object of Statement class int flag=0; FetchData() { frame1 = new JFrame(); frame1.setTitle("Search Database");//setting the title of first JFrame frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//setting default close operation GridBagLayout bagLayout = new GridBagLayout();//creating object of GridBagLayout GridBagConstraints bagConstraints = new GridBagConstraints();//creating object of GridBagConstratints frame1.setSize(500, 300);//setting the size of first JFrame frame1.setLayout(bagLayout);//setting the layout to GridBagLayout of first JFrame bagConstraints.insets = new Insets(15, 40, 0, 0);//Setting the padding between the components and neighboring components //Setting the property of JLabel and adding it to the first JFrame nameLabel = new JLabel("Enter Username"); bagConstraints.gridx = 0; bagConstraints.gridy = 0; frame1.add(nameLabel, bagConstraints); //Setting the property of JTextfield and adding it to the first JFrame nameTextField = new JTextField(15); bagConstraints.gridx = 1; bagConstraints.gridy = 0; frame1.add(nameTextField, bagConstraints); //Setting the property of JButton(Fetch Data) and adding it to the first JFrame fetchButton = new JButton("Fetch Data"); bagConstraints.gridx = 0; bagConstraints.gridy = 1; bagConstraints.ipadx = 60; frame1.add(fetchButton, bagConstraints); //Setting the property of JButton(Reset Data) and adding it to the second JFrame resetButton = new JButton("Reset Data"); bagConstraints.gridx = 1; bagConstraints.gridy = 1; frame1.add(resetButton, bagConstraints); //adding ActionListener to both buttons fetchButton.addActionListener(this); resetButton.addActionListener(this); frame1.setVisible(true);//Setting the visibility of First JFrame frame1.validate();//Performing relayout of the First JFrame } public static void main(String[] args) { new FetchData(); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == fetchButton) { String userName = nameTextField.getText().toString();//getting text of username text field and storing it in a String variable frameSecond(userName);//passing the text value to frameSecond method } if (e.getSource() == resetButton) { nameTextField.setText("");//resetting the value of username text field } } public void frameSecond(String userName) { //setting the properties of second JFrame frame2 = new JFrame("Database Results"); frame2.setLayout(new FlowLayout()); frame2.setSize(400, 400); //Setting the properties of JTable and DefaultTableModel defaultTableModel = new DefaultTableModel(); table = new JTable(defaultTableModel); table.setPreferredScrollableViewportSize(new Dimension(300, 100)); table.setFillsViewportHeight(true); frame2.add(new JScrollPane(table)); defaultTableModel.addColumn("Username"); defaultTableModel.addColumn("Roll No"); defaultTableModel.addColumn("Department"); try { connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDatabase", "root", "root");//Crating connection with database statement = connection.createStatement();//crating statement object String query = "select * from STUDENT where USERNAME = '" + userName + "'";//Storing MySQL query in A string variable ResultSet resultSet = statement.executeQuery(query);//executing query and storing result in ResultSet while (resultSet.next()) { //Retrieving details from the database and storing it in the String variables String name = resultSet.getString("USERNAME"); String roll = resultSet.getString("ROLLNO"); String dept = resultSet.getString("DEPARTMENT"); if (userName.equalsIgnoreCase(name)) { flag = 1; defaultTableModel.addRow(new Object[]{name, roll, dept});//Adding row in Table frame2.setVisible(true);//Setting the visibility of second Frame frame2.validate(); break; } } if (flag == 0) { JOptionPane.showMessageDialog(null, "No Such Username Found");//When invalid username is entered } } catch (SQLException throwables) { throwables.printStackTrace(); } } } |
- Now run your program, Enter the username and click on the “Fetch Data” button.
- As soon as you click on the “Fetch Data” button, the new JFrame will show up with the table inside it and the details of the particular student as shown in the figure below.
- Now again Run the program and click an invalid username then the message dialog box will show up with the message ” No such username found”.
- In the same way, you can also use the Reset Button, and it will work perfectly fine.
How to Retrieve Data From Database and Display it in JTable Using Java Swing Source Code
So this was all from this tutorial, Feel free to comment down below if you have any query regarding this post. Thank You
People are also Reading…..
- Why Pointers are not Used in Java
- Menu Driven Program in Java Using Switch Case
- How to Create Calculator in Java Swing
- How to Create Tic Tac Toe Game in Java
- How to Create Login Form in Java Swing
- Registration Form In Java with Database Connectivity
- How to Create Splash Screen In Java
- How to Create Mp3 Player in Java
Dear Mehtab Hameed,
Assalamualaikum Rahmatullahi vabarakatahu!
Your tutorial to retrieve data from database and display in jtable is excellent.
Thank you very much. May Allah bless you with success in this world and in the Aakhirat.
I am trying to make namaz timetable in java and MS Access. My Syntax select * from table salat
where date = Date().i.e.Todays date is not working. Please help me to use correct date() syntax.
My email is [email protected]. My No +91 98450 37286.
Jazakallahu Khair
This is very useful !!!!!
Thank you so much..