我通过验证来编写此代码以更改密码。问题是,当我单击jbutton
更改密码时,它可以正常工作并成功更改了数据库上的密码,并且还显示了jOptionpane
信息消息。
但是在执行此步骤之后,错误消息功能jOptionpane
会持续显示。我试图找到代码错误的地方。但还不能。
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 tch_data");
while(rs.next()) {
String userid = rs.getString("user_id");
String pass = rs.getString("password");
if(user_id.equals(userid) && cur_pass.equals(pass)) {
Statement s1 = c.createStatement();
s1.executeUpdate("UPDATE tch_data SET password='"+new_pass+"' WHERE user_id='"+user_id+"'");
JOptionPane.showMessageDialog(new view.AdminPrivacy(), "Password Succesfully Changed!", null, JOptionPane.INFORMATION_MESSAGE);
}else {
JOptionPane.showMessageDialog(new view.AdminPrivacy(), "Error : Invalid Data.", "Error Message", JOptionPane.ERROR_MESSAGE);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
最佳答案
成功更改密码后,应使用break语句退出while循环。 while循环内的else语句也应删除,并放置在循环外。应该设置一个布尔标志,以确定是否成功进行了密码更改,并且在循环之外检查了该条件,例如:
try {
Connection c = DBConnection.dbconmethod();
Statement s = c.createStatement();
ResultSet rs = s.executeQuery("SELECT * from tch_data");
boolean success = false; // **** Added Code ****
while(rs.next() && success == false) {
String userid = rs.getString("user_id");
String pass = rs.getString("password");
if(user_id.equals(userid) && cur_pass.equals(pass)) {
Statement s1 = c.createStatement();
s1.executeUpdate("UPDATE tch_data SET password='"+new_pass+"' WHERE user_id='"+user_id+"'");
success = true; // **** Added Code ****
JOptionPane.showMessageDialog(new view.AdminPrivacy(), "Password Succesfully Changed!", null, JOptionPane.INFORMATION_MESSAGE);
break; // **** Added Code ****
}
}
// **** Added Code ****
if (!success) {
JOptionPane.showMessageDialog(new view.AdminPrivacy(), "Error : Invalid Data.", "Error Message", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e) { e.printStackTrace(); }