修改这段代码实现查询 JButton b4 = new JButton("查询"); b4.setPreferredSize(new Dimension(150,30)); b4.addActionListener(new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { String id = t0.getText(); Connection con = DBUtil.getConnect(); String sql = "SELECT * FROM tushu WHERE id = ?"; try { PreparedStatement ps = con.prepareStatement(sql); ps.setString(1,id); int result = ps.executeUpdate(); if (result>0){ JOptionPane.showMessageDialog(QueryDialog.this,"删除成功"); // new StudentFrame(); dataChangelisenter.dataChange(); dispose(); }else { JOptionPane.showMessageDialog(QueryDialog.this,"删除失败"); } } catch (SQLException throwables) { throwables.printStackTrace(); } } });
时间: 2023-12-12 22:03:02 浏览: 84
这段代码是一个查询按钮的实现,但是其中的代码实现的是删除数据,需要进行修改才能实现查询功能。下面是修改后的代码:
```
JButton b4 = new JButton("查询");
b4.setPreferredSize(new Dimension(150, 30));
b4.addActionListener(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
String id = t0.getText();
Connection con = DBUtil.getConnect();
String sql = "SELECT * FROM tushu WHERE id = ?";
try {
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, id);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
String name = rs.getString("name");
String author = rs.getString("author");
String publish = rs.getString("publish");
String price = rs.getString("price");
JOptionPane.showMessageDialog(QueryDialog.this, "查询成功\n书名:" + name + "\n作者:" + author + "\n出版社:" + publish + "\n价格:" + price);
} else {
JOptionPane.showMessageDialog(QueryDialog.this, "查询失败,未找到该书籍");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
});
```
修改后的代码中,首先获取用户输入的书籍ID,然后通过PreparedStatement对象执行查询语句,将结果保存到ResultSet对象中。如果ResultSet对象中有数据,则将数据取出并弹出提示框显示,否则提示未找到该书籍。
阅读全文