我无法启动else语句。此代码位于GUI中,该GUI在文本字段中输入用户名后向用户发送电子邮件。如果在SQL数据库中找到它,它将检索电子邮件地址,一切都很好。如果输入的用户名不在数据库中,则不执行任何操作,我没有收到错误消息,只是挂起。以下是提交按钮
中的代码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"
+ "info@somewhere.com.au.");
}//end else
} //end while
close();
}//end try //catch statement follows
期待谢谢......
谢谢大家的帮助。它现在有效,你已经有效地解决了我的另一个问题。这是最终的代码。再次感谢。
int count = 0;
而(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"
+ "info@somewhere.com.au.");
}//end else
// } //end while
答案 0 :(得分:1)
我认为没有必要在while循环中检查用户名的相等性,因为您已经使用该名称进行查询。
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"
+ "info@somewhere.com.au.");
}//end else
答案 1 :(得分:0)
不是完整的代码......而是你想要的代码!
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"
+ "info@somewhere.com.au.");
}