Reputation: 1
I am having trouble getting the else statement to kick in. This code is within a GUI which sends an email to the user after the username is entered in the text field. If it is found in the SQL database, it retrieves the email address and all is good. If a username is entered in which is not in the database, it does nothing, I don't get an error message, it just hangs. Here is the code from the submit button
jButtonSubmit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt)
{
try
{
username = (jTextFieldUsername.getText());
connection = DriverManager.getConnection(DATABASE_URL, USERNAME, PASSWORD);
query = "SELECT User_userName, User_email FROM user_details WHERE " +
"User_userName = '"+username+"'";
PreparedStatement stm = connection.prepareStatement(query);
rs =stm.executeQuery();
while (rs.next())
{
String eMail = rs.getString ("User_email");
if (username.equals(rs.getString("User_userName")))
{
JOptionPane.showMessageDialog(frame, "An email with your password "
+ "has been sent \nto " + eMail);
}// end if
else
{
JOptionPane.showMessageDialog(frame, "Incorrect username. If "
+ "you are unable to login\n"
+ "with your current username, please contact us on\n"
+ "[email protected].");
}//end else
} //end while
close();
}//end try //catch statement follows
In anticipation thanks....
Thank you all for your help. It works now and you have effectively solved another of my problems. Here is the final code. Thanks again.
int count = 0;
while(rs.next()){
eMail = rs.getString ("User_email");
count++;}
if (count != 0)
{
JOptionPane.showMessageDialog(frame, "An email with your password "
+ "has been sent \nto " + eMail);
}// end if
else
{
JOptionPane.showMessageDialog(frame, "Incorrect username. If "
+ "you are unable to login\n"
+ "with your current username, please contact us on\n"
+ "[email protected].");
}//end else
// } //end while
Upvotes: 0
Views: 120
Reputation: 116
I think there is no need to check the equality of username in while loop because you already query with that name.
int count=0;
while (rs.next())
{
count++;
}
if (count>0)
{
JOptionPane.showMessageDialog(frame, "An email with your password "
+ "has been sent \nto " + eMail);
}// end if
else
{
JOptionPane.showMessageDialog(frame, "Incorrect username. If "
+ "you are unable to login\n"
+ "with your current username, please contact us on\n"
+ "[email protected].");
}//end else
Upvotes: 1
Reputation: 2166
Not the full code...but the ones you want!
query = "SELECT User_userName, User_email FROM user_details WHERE User_userName = ?";
PreparedStatement stm = connection.prepareStatement(query);
stm.setString(1, username);
rs =stm.executeQuery();
..
..
//And to check if rs is null
if(rs!=null){
while(rs.next()){
....
}
}
else{
JOptionPane.showMessageDialog(frame, "Incorrect username. If "
+ "you are unable to login\n"
+ "with your current username, please contact us on\n"
+ "[email protected].");
}
Upvotes: 0