改错if(e.getSource()==btn_delete) { try { Class.forName(driver); con=DriverManager.getConnection(url,"root",""); cmd=con.createStatement(); String sql="select * from student where sno='" + txt_no.getText() + "'"; rs=cmd.executeQuery(sql); if(rs.next()) if(rs.getString(1).equals(txt_no.getText())==false) System.out.print(" 1 "); con.close(); }catch(Exception e1) { System.out.println(e1); }
时间: 2024-03-18 13:38:30 浏览: 60
在代码中没有明显的错误,但是可以优化一下逻辑。在查询语句中,已经通过 `sno` 字段来查询学生信息了,所以不需要在查询结果中再次判断 `sno` 是否等于输入的学号。可以将 `if(rs.next())` 和 `if(rs.getString(1).equals(txt_no.getText())==false)` 合并成一个语句,如下所示:
```
if (rs.next() && !rs.getString("sno").equals(txt_no.getText())) {
System.out.print(" 1 ");
}
```
此外,`con` 和 `cmd` 都需要在使用完毕后关闭,可以在 `finally` 代码块中关闭,以确保资源被正确释放。完整代码如下:
```
if (e.getSource() == btn_delete) {
try {
Class.forName(driver);
con = DriverManager.getConnection(url, "root", "");
cmd = con.createStatement();
String sql = "select * from student where sno='" + txt_no.getText() + "'";
rs = cmd.executeQuery(sql);
if (rs.next() && !rs.getString("sno").equals(txt_no.getText())) {
System.out.print(" 1 ");
}
} catch (Exception e1) {
System.out.println(e1);
} finally {
try {
if (rs != null) {
rs.close();
}
if (cmd != null) {
cmd.close();
}
if (con != null) {
con.close();
}
} catch (Exception e2) {
System.out.println(e2);
}
}
}
```
阅读全文