用JFrame实现查询表中的内容并用JTable输出
时间: 2024-03-11 08:43:41 浏览: 77
好的,我可以为您提供一个简单的示例代码,用JFrame实现查询表中的内容并用JTable输出。以下是代码:
```java
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
public class QueryTable extends JFrame {
private JLabel label;
private JTextField textField;
private JButton button;
private JTable table;
private DefaultTableModel tableModel;
public QueryTable() {
setTitle("查询表中的内容");
setSize(500, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
label = new JLabel("请输入要查询的表名:");
textField = new JTextField(20);
button = new JButton("查询");
tableModel = new DefaultTableModel();
table = new JTable(tableModel);
JScrollPane scrollPane = new JScrollPane(table);
JPanel topPanel = new JPanel();
topPanel.add(label);
topPanel.add(textField);
topPanel.add(button);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String tableName = textField.getText();
if (tableName != null && !tableName.equals("")) {
try {
// 连接数据库
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
Statement stmt = conn.createStatement();
// 查询表中的所有内容
String sql = "SELECT * FROM " + tableName;
ResultSet rs = stmt.executeQuery(sql);
// 获取表的列数
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
// 将查询结果放入表格中
tableModel.setColumnCount(0);
tableModel.setRowCount(0);
for (int i = 1; i <= columnCount; i++) {
tableModel.addColumn(metaData.getColumnLabel(i));
}
while (rs.next()) {
Object[] rowData = new Object[columnCount];
for (int i = 1; i <= columnCount; i++) {
rowData[i - 1] = rs.getObject(i);
}
tableModel.addRow(rowData);
}
// 关闭连接
rs.close();
stmt.close();
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
});
add(topPanel, BorderLayout.NORTH);
add(scrollPane, BorderLayout.CENTER);
setVisible(true);
}
public static void main(String[] args) {
new QueryTable();
}
}
```
这个程序会打开一个JFrame窗口,上面有一个文本框和一个查询按钮,用户输入要查询的表名后,点击查询按钮,程序会连接数据库并查询指定表中的所有内容,将查询结果放入表格中并输出。
阅读全文