LAB ACTIVITY 4E
Manipulates JDBC connectivity (JTable).
Manipulates JDBC connectivity (JTable).
Learning Outcomes
By the end of this lab, students should be able to :
Understand how to connect to a database using JDBC.
Write a Java program using JDBC.
Hardware/ Software : Personal Computer, Java Development Kit version X.x.x., NetBeans IDE 12.0
Activity Outcome: Student know how to use JDBC
You first need to create a database in MySQL and a table to store book records. Use the following SQL commands:
Now let's create the GUI using Java Swing. This will be the interface where you can enter book details and display them in a table.
Here's the Java code for the GUI:
In this step, we will add an event listener to the Insert button so that, when clicked, it will retrieve data from the text fields and insert it into the MySQL database.
This step focuses on retrieving data from the database and displaying it in a table using the SELECT statement. Here, you will create a viewDb class with a method viewDatabase() that connects to the MySQL database, fetches the data from the book_details table, and returns it as a two-dimensional string array, which can then be displayed in a JTable.
Now that we have the data retrieval mechanism in place (from the previous step), we need to display the data in a JTable and also provide a way to update the table when new data is inserted. This will involve:
Calling the function to display the data in JTable.
Creating a method called updateTable() that refreshes the table by reloading data from the database.
Here’s how you can call the viewDatabase() method to load the data into your JTable.
This method is responsible for updating the JTable whenever new data is inserted or modifications are made. The table should be refreshed to reflect the latest data from the database.
You can call the updateTable() function in various parts of your program, such as after inserting new data or when initializing the GUI to load the current data in the database.
For example:
After inserting data:
Refer to the video below for the video version.