NetBeans15登录页executeQuery()异常终止,无法执行else分支求助
登录验证错误输入无响应的问题修复
你这段代码的核心问题是没有给PreparedStatement的占位符赋值,加上空catch块吞了异常,导致错误输入时抛出SQL异常但无法察觉,代码直接终止,后续逻辑都不执行。
问题分析
你写了带?参数占位符的SQL语句,但没有用setXxx方法把输入的卡号和PIN传递给PreparedStatement。执行查询时数据库会因为参数缺失抛出SQLException,而你的catch块什么都没做,异常被静默处理,导致Rs= St.executeQuery();之后的打印、分支判断都不会执行。
修复后的完整代码
Connection Con = null; PreparedStatement pst = null; ResultSet Rs = null; // 移除多余的Statement St类成员(你实际用的是PreparedStatement) private void LoginTbMouseClicked(java.awt.event.MouseEvent evt) { if(UnameTb.getText().isEmpty() || PasswordTb.getText().isEmpty()){ JOptionPane.showMessageDialog(this, "Enter Card and PIN Number"); }else{ String Query1 = "select * from AccountTbl where `Card Number`=? and `PIN`=?"; try{ Con = DriverManager.getConnection("jdbc:mysql://localhost:3306/CREDITDEBITDb","Amaity","Alok@2022"); pst = Con.prepareStatement(Query1); // 给SQL占位符赋值:第一个?对应卡号,第二个?对应PIN pst.setString(1, UnameTb.getText()); // 如果你的PIN字段是数字类型,改用setInt: // pst.setInt(2, Integer.parseInt(PasswordTb.getText())); pst.setString(2, PasswordTb.getText()); Rs = pst.executeQuery(); System.out.println("Resultset: " + Rs); if(Rs.next()){ new MainMenu().setVisible(true); this.dispose(); }else{ JOptionPane.showMessageDialog(this, "Wrong Card Number or PIN"); } }catch(SQLException | HeadlessException e){ // 不要吞异常,打印错误信息方便排查 e.printStackTrace(); JOptionPane.showMessageDialog(this, "登录出错:" + e.getMessage()); }finally{ // 必须关闭数据库资源,避免连接泄漏 try { if(Rs != null) Rs.close(); if(pst != null) pst.close(); if(Con != null) Con.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
关键修复点
- 给PreparedStatement赋值:必须通过
setString/setInt等方法将用户输入传递给SQL的占位符,否则数据库无法执行合法查询。 - 取消空catch块:添加异常打印或弹窗提示,避免隐藏错误,方便调试。
- 避免变量覆盖:移除重复定义的
PreparedStatement St,使用已声明的pst成员变量。 - 关闭数据库资源:在finally块中统一关闭ResultSet、PreparedStatement和Connection,防止数据库连接泄漏。
- 修正拼写错误:将原代码中的"Wrong Card Numner or PIN"改为正确的"Wrong Card Number or PIN"。
内容的提问来源于stack exchange,提问作者user19121278
相关产品推荐
相关产品推荐

