How to display MySQL table data in JTable?

Member

by ramon , in category: Java , a year ago

How to display MySQL table data in JTable?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by berta , a year ago

@ramon 

To display MySQL table data in a JTable, you can follow these steps:

  1. Import the necessary packages:
1
2
3
import java.sql.*;
import javax.swing.*;
import javax.swing.table.*;


  1. Connect to the MySQL database:
1
2
3
4
5
6
7
Connection conn = null;
try {
    // Replace "username" and "password" with your MySQL login credentials
    conn = DriverManager.getConnection("jdbc:mysql://localhost/database_name?user=username&password=password");
} catch (SQLException e) {
    e.printStackTrace();
}


  1. Execute a SELECT query to retrieve the data from the table:
1
2
3
String query = "SELECT * FROM table_name";
Statement st = conn.createStatement();
 ResultSet rs = st.executeQuery(query);


  1. Create a JTable and a DefaultTableModel to hold the data:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
JTable table = new JTable();
DefaultTableModel model = new DefaultTableModel();

// Get the column names from the ResultSet metadata
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
    model.addColumn(metaData.getColumnName(i));
}

// Add the rows to the DefaultTableModel
while (rs.next()) {
    Object[] row = new Object[columnCount];
    for (int i = 1; i <= columnCount; i++) {
        row[i - 1] = rs.getObject(i);
    }
    model.addRow(row);
}

// Set the model of the JTable
table.setModel(model);


  1. Add the JTable to your UI:
1
2
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);


That's it! You should now be able to see the MySQL table data displayed in the JTable.


Note: This is just a basic example. You may want to add error handling, handle pagination, and customize the appearance of the JTable.