"如果"和" ResultSet"代码错误:SQLExpection

时间:2017-01-20 16:44:32

标签: java database resultset sqlexception

请帮帮我。此代码没有显示错误,但是当它运行并完成时显示错误。

这是我的代码:

private void jBtn_UpdateActionPerformed(java.awt.event.ActionEvent evt {                                            

String user_id = txt_UserID.getText();

String cur_pass = txt_CurrentPassword.getText();

String new_pass = txt_NewPassword.getText();
    try{
        Connection c = DBConnection.dbconmethod();
        Statement s = c.createStatement();
        ResultSet rs = s.executeQuery("SELECT * from admin_data");

    while(rs.next()){
        String userid = rs.getString("user_id");
        String pass = rs.getString("password");
        if(user_id.equals(userid) && cur_pass.equals(pass)){
            s.executeUpdate("UPDATE admin_data SET password='"+new_pass+"'");
            UIManager.put("OptionPane.messageFont", new Font("Monospaced", Font.BOLD, 22));
            JOptionPane.showMessageDialog(new view.AdminPrivacy(), "Password Succesfully Changed!", null, JOptionPane.INFORMATION_MESSAGE);

        txt_UserID.setText(null);
        txt_CurrentPassword.setText(null);
        txt_NewPassword.setText(null);

        }else{
            UIManager.put("OptionPane.messageFont", new Font("Monospaced", Font.BOLD, 22));
            JOptionPane.showMessageDialog(new view.AdminPrivacy(), "Error : Invalid Data.", "Error Message", JOptionPane.ERROR_MESSAGE);
        }

        c.close();
        s.close();

    }   

    } catch (Exception e) {
       e.printStackTrace();       
    }

}       

这是错误:https://i.stack.imgur.com/8COxh.png

2 个答案:

答案 0 :(得分:0)

您正在关闭while循环中的连接和语句。

while(rs.next()) {
    ...
    c.close();
    s.close();
}

尝试使用finally子句(在catch (Exception)子句之后)并在那里关闭这些语句或使用ARM block

ARM Block :这也应该自动处理你的连接关闭。

try(Connection c = DBConnection.dbconmethod();
        Statement s = c.createStatement();) {
     ...
}
catch(Exception e) { ... }

答案 1 :(得分:0)

您每次迭代都会关闭connectionstatement,所以这里有一个安全的示例,您应该如何关闭连接:

    try {
        //your code
    } catch (SQLException e) {
        //part of exception
    } finally {
        //close your statement and your connection
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException ex) {
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException ex) {
            }
        }
    }