java JFrame 前端显示数据库查询结果
时间: 2024-03-06 15:46:52 浏览: 21
要在Java JFrame 前端显示数据库查询结果,你可以使用JTable组件。JTable是Swing库中用于显示表格数据的组件,它可以方便地将结果集中的数据显示在表格中。
以下是一个简单的示例代码,它连接到MySQL数据库并从“mytable”表中检索数据,并将其显示在JTable中:
```java
import java.awt.BorderLayout;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
public class DisplayData extends JFrame {
private JTable table;
private DefaultTableModel model;
public DisplayData() {
setTitle("Display Data");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create the table model
model = new DefaultTableModel();
model.addColumn("ID");
model.addColumn("Name");
model.addColumn("Age");
// Create the table and set the model
table = new JTable(model);
// Add the table to a scroll pane
JScrollPane scrollPane = new JScrollPane(table);
// Add the scroll pane to the frame
getContentPane().add(scrollPane, BorderLayout.CENTER);
// Set the frame size and make it visible
setSize(400, 300);
setVisible(true);
// Populate the table with data
populateTable();
}
private void populateTable() {
try {
// Connect to the database
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "username", "password");
// Prepare the SQL statement
String sql = "SELECT * FROM mytable";
Statement stmt = conn.createStatement();
// Execute the query and get the result set
ResultSet rs = stmt.executeQuery(sql);
// Loop through the result set and add the data to the table model
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
model.addRow(new Object[] { id, name, age });
}
// Close the connection and release resources
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
System.out.println("Error: " + e.getMessage());
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new DisplayData();
}
});
}
}
```
在这个示例中,我们创建了一个JFrame窗口,将JTable添加到其中,并使用DefaultTableModel作为数据模型。然后,我们定义了一个populateTable()方法,该方法连接到数据库,执行SELECT查询,并将结果集中的数据添加到表格中。
当你运行这个应用程序时,它将显示一个带有表格的窗口,其中包含从数据库检索的数据。