Java swing 连接数据库后模糊查询代码
时间: 2023-09-17 22:13:40 浏览: 187
java实现的连接数据库及模糊查询功能示例
这里是一个使用 Java Swing 和 JDBC 连接数据库后进行模糊查询的示例代码:
```
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
import javax.swing.table.*;
public class FuzzyQueryExample extends JFrame {
private JTextField queryTextField;
private JTable resultTable;
public FuzzyQueryExample() {
super("Fuzzy Query Example");
// 创建 UI 组件
JLabel queryLabel = new JLabel("Enter a keyword to search:");
queryTextField = new JTextField(20);
JButton queryButton = new JButton("Search");
resultTable = new JTable();
// 将组件添加到容器中
JPanel controlPanel = new JPanel(new FlowLayout());
controlPanel.add(queryLabel);
controlPanel.add(queryTextField);
controlPanel.add(queryButton);
JScrollPane resultScrollPane = new JScrollPane(resultTable);
Container contentPane = getContentPane();
contentPane.add(controlPanel, BorderLayout.NORTH);
contentPane.add(resultScrollPane, BorderLayout.CENTER);
// 添加事件处理程序
queryButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
performQuery();
}
});
// 设置窗口属性
setSize(400, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
private void performQuery() {
String keyword = queryTextField.getText().trim();
if (keyword.isEmpty()) {
JOptionPane.showMessageDialog(this, "Please enter a keyword to search.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password")) {
String sql = "SELECT * FROM products WHERE name LIKE ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, "%" + keyword + "%");
ResultSet rs = stmt.executeQuery();
DefaultTableModel model = new DefaultTableModel();
model.addColumn("ID");
model.addColumn("Name");
model.addColumn("Price");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
double price = rs.getDouble("price");
model.addRow(new Object[] { id, name, price });
}
resultTable.setModel(model);
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "Error executing query: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
public static void main(String[] args) {
new FuzzyQueryExample();
}
}
```
这个示例程序包括一个带有文本框、按钮和表格的简单 UI。当用户点击按钮时,程序将从数据库中查询包含指定关键字的记录,并将结果显示在表格中。在这个示例中,我们使用了 MySQL 数据库,但您可以根据需要替换为其他数据库。请确保已添加正确的 JDBC 驱动程序。
阅读全文