you’re reading...

J2SE

Populate data from database into JTable in Netbeans

How to populate data from database into JTable in Netbeans?

Suppose we had a table called Employee in our MS Access database and we want to retrieve and display all the data in a JTable component using NetBeans IDE. How to do that and what are the codes that we need to modify?

In this example, i am using an MS Access database and created a table called employee. This table contains fileds empid, name, position and department. Some sample data was added too.

Let’s follow the steps to do it:

Step 1: Create the table in MS Access and make sure you put the database file inside your NetBeans Project Folder.

Step 2: Create database engine to retrieve data from the Access table:
Create a class called DBEngine to retrieve the data from Access (Make sure you had created a new NetBeans Project first for this tutorial) Note: i used project.engine package for example only. You are free to create yours.

The following code is done in the DBEngine.java. Basically its a class to retrieve all the data from Employee table using JDBC.

package project.engine;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Vector;

/**
*
* @author cgg
*/
public class DBEngine
{
/**
* Connect to database
* @return Connection to database
* @throws java.lang.Exception
*/
public Connection dbConnection()throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String myDB ="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=pay.MDB";
return DriverManager.getConnection(myDB,"","");
}

/**
* This method will load vector of vector of string and load all the data in
* the vector
* @return vector of vector of string
* @throws java.lang.Exception
*/
public Vector getEmployee()throws Exception
{
Vector<Vector<String>> employeeVector = new Vector<Vector<String>>();

Connection conn = dbConnection();
PreparedStatement pre = conn.prepareStatement("select * from employee");

ResultSet rs = pre.executeQuery();

while(rs.next())
{
Vector<String> employee = new Vector<String>();
employee.add(rs.getString(1)); //Empid
employee.add(rs.getString(2)); //name
employee.add(rs.getString(3)); //position
employee.add(rs.getString(4)); //department
employeeVector.add(employee);
}

/*Close the connection after use (MUST)*/
if(conn!=null)
conn.close();

return employeeVector;
}
}

Step 3: Now create the GUI with a JTable component inside it.

Create a new JFrame Form


I named the class TableExample and created under project.gui package.


Add a JTable component onto the Frame.

Step 4: After inserting the JTable component, switch to Source view, we need to insert coding to retrieve data from database.


Add a JTable component onto the Frame.

Step 5: Add the following codes as shown below.
Code you need to add are:
line 03 and 04 (import packages)
line 12 and 13 (instantiate two Vector objects, to hold table data and table header)
line 16 (add throws Exception)
line 19 to 27 (to populate data from database into the Vector object and also initialize the table header Vector object)

package project.gui;

import java.util.Vector;
import project.engine.DBEngine;

/**
 *
 * @author  cgg
 */
public class TableExamples extends javax.swing.JFrame {
    
    private Vector<Vector<String>> data; //used for data from database
    private Vector<String> header; //used to store data header
    
    /** Creates new form TableExamples */
    public TableExamples() throws Exception{
        
        //get data from database
        DBEngine dbengine = new DBEngine();
        data = dbengine.getEmployee();
        
        //create header for the table
        header = new Vector<String>();
        header.add("EmpID"); //Empid
        header.add("Name"); // employee name
        header.add("Position"); // employee position
        header.add("Department"); // employee department
        
        initComponents();
}
.
.
.
.

Step 6: switch back to design view and right click on the JTable component, then select the Customize Code button.


Choose customize code option to customize the codes.

The customize code page will be shown as follow:

Customize code page

Step 7: change the default code into custom property and change the code as follow:

change the codes to let the table to populate the Vector object we created just now.

Step 8: you need to update the main method to handle exception using try… catch block
Search for the main method in the code view and modify it with adding try…catch block as shown follow:

/**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try
                {
                    new TableExamples().setVisible(true);
                }catch(Exception e){e.printStackTrace();}
            }
        });
    }

Step 9: now build and run the project or the file, you should be able to get the following output:

Output:
Table populated with data from database.

That’s it. Give it a try.
Note: in this example, what i had done is just to populate the data from database into JTable component through Netbeans IDE. As u can see, it deals with purpose of displaying data only. if you want more actions to be done such as update, delete, etc, you need to use proper data binding techniques in Netbeans.