How to show data from MySQL in JTable?

Member

by ward , in category: Java , a year ago

How to show data from MySQL in JTable?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by lavina.marks , a year ago

@ward 

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

  1. Connect to the MySQL database using the JDBC driver. You will need to include the JDBC driver in your classpath and create a connection to the database using the DriverManager class.
  2. Create a Statement object from the Connection object. This will allow you to execute SQL statements against the database.
  3. Execute a SELECT statement to retrieve the data you want to display in the JTable. You can use the executeQuery() method of the Statement object to execute the SELECT statement and retrieve the ResultSet object.
  4. Create a DefaultTableModel object and set it as the model for the JTable. The DefaultTableModel class allows you to easily add rows and columns to the table.
  5. Iterate over the ResultSet object and add each row of data to the DefaultTableModel using the addRow() method.
  6. Set the DefaultTableModel as the model for the JTable using the setModel() method of the JTable.


Here is an example of how this might look in code:

 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
// Step 1: Connect to the database
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "user";
String password = "pass";

Connection conn = DriverManager.getConnection(url, username, password);

// Step 2: Create a statement
Statement stmt = conn.createStatement();

// Step 3: Execute a SELECT query
ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");

// Step 4: Create the DefaultTableModel
DefaultTableModel model = new DefaultTableModel();

// Step 5: Iterate over the ResultSet and add rows to the table model
while (rs.next()) {
    Object[] row = new Object[2];
    row[0] = rs.getInt("id");
    row[1] = rs.getString("name");
    model.addRow(row);
}

// Step 6: Set the table model as the model for the JTable
JTable table = new JTable();
table.setModel(model);


I hope this helps! Let me know if you have any questions.

by mohamed_lind , 3 months ago

@ward 

This answer is correct. I would like to add that it is important to close the connection and the statement after finishing using them to avoid resource leaks. Here is an example of how to add the closing statements to the code:


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16


// Step 6: Set the table model as the model for the JTable JTable table = new JTable(); table.setModel(model);


// Step 7: Close the connection, statement and result set rs.close(); stmt.close(); conn.close();


By closing these resources, you ensure that they are released and available for other parts of your code or other applications to use.