编写一个javaGUI查询功能的代码连接mySQL实现数据库查询,并在界面上显示查询出来的内容
时间: 2024-10-10 16:14:05 浏览: 103
在Java中编写一个GUI应用程序连接MySQL并实现数据查询通常涉及到几个步骤:首先创建JFrame窗口,然后设置JButton来触发查询操作,最后通过JTable展示查询结果。以下是一个简单的例子,我们将使用Swing库来构建界面,`java.sql`包处理数据库连接,以及`javax.swing.table.DefaultTableModel`来填充表格。
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class MySQLQueryApp extends JFrame {
private JButton queryBtn;
private JTable jTable;
private DefaultTableModel model;
public MySQLQueryApp() {
setTitle("MySQL Query App");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new FlowLayout());
queryBtn = new JButton("查询");
queryBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String sql = "SELECT * FROM your_table_name"; // 替换为你的表名
executeQuery(sql);
}
});
panel.add(queryBtn);
jTable = new JTable(model);
jTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
panel.add(jTable);
add(panel);
setVisible(true);
}
private void executeQuery(String sql) {
try {
Class.forName("com.mysql.cj.jdbc.Driver"); // 加载MySQL驱动
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/your_database", // 数据库URL
"username", "password" // 用户名和密码
);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
model.setDataVector(new Object[][]{}, new Object[] {"Column1", "Column2"}); // 假设有两个列
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
model.addRow(new Object[]{id, name});
}
rs.close();
stmt.close();
conn.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MySQLQueryApp());
}
}
阅读全文