Java MySQL swing 查找功能模糊查找的代码实现
时间: 2024-03-18 16:40:15 浏览: 65
下面是一个简单的Java Swing界面,实现MySQL数据库中模糊查找功能的代码:
```java
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
public class SearchDemo extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JPanel panel;
private JLabel label;
private JTextField textField;
private JButton btnSearch;
private JTable table;
private DefaultTableModel model;
private Connection conn;
private PreparedStatement pstmt;
private ResultSet rs;
public SearchDemo() {
super("模糊查找");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 创建界面组件
panel = new JPanel();
label = new JLabel("查找:");
textField = new JTextField(20);
btnSearch = new JButton("查找");
btnSearch.addActionListener(this);
model = new DefaultTableModel();
table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
// 添加组件到面板
panel.add(label);
panel.add(textField);
panel.add(btnSearch);
add(panel, BorderLayout.NORTH);
add(scrollPane, BorderLayout.CENTER);
// 创建数据库连接
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
// 显示界面
setSize(600, 400);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnSearch) {
// 清空表格数据
model.setRowCount(0);
try {
// 模糊查找
String sql = "SELECT * FROM students WHERE name LIKE ?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "%" + textField.getText() + "%");
rs = pstmt.executeQuery();
// 显示查询结果
while (rs.next()) {
Object[] row = { rs.getInt("id"), rs.getString("name"), rs.getInt("age") };
model.addRow(row);
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
new SearchDemo();
}
}
```
在上面的代码中,我们创建了一个简单的界面,包括一个标签、一个文本框、一个按钮和一个表格。当用户输入要查找的内容并点击查找按钮时,程序会连接到MySQL数据库,执行模糊查找(使用LIKE语句),并将结果显示在表格中。当用户关闭窗口时,程序会关闭数据库连接。
阅读全文