赞
踩
What I'm trying to do is:
Accept username(uname) and password(passw) as an input from the user.
Using ResultSet, retrieve the only tuple, to which username in the database and username given by user suits. This tuple will contain username and password.
If the password given by user also suits the password in the database, the display the message that both creadentials are correct else one of them is wrong.
Everything works fine except in one case. When the username itself is wrong, the mysql will not find the attribute at all and will give this error: java.sql.SQLException: Illegal operation on empty result set.
The code is:
ok.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String uname=jf1.getText();
String passw=jf2.getText();
String n;
String m;
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/authentication?" + "user=root&password=letmein");
PreparedStatement stmt=conn.prepareStatement("Select * from admin where id = ?");
stmt.setString(1,uname);
ResultSet rs=stmt.executeQuery();
rs.next();
n=rs.getString("id");
m=rs.getString("pass");
conn.close();
if(n.equalsIgnoreCase(uname) && m.equalsIgnoreCase(passw))
{
JOptionPane.showMessageDialog(null,"Username and password is correct");
}
else
{
JOptionPane.showMessageDialog(null,"Username or password is not correct");
}
}
catch(Exception ex)
{
System.out.println(ex);
}
}//end of actionperformed
});//end of actionlistener
Is there any way I can do both operations at a time (before closing the connection with database)?. If not, what's the alternative method?
解决方案
You are supposed to use the result of rs.next() :
if (rs.next()) {
n=rs.getString("id");
m=rs.getString("pass");
}
If rs.next() returns false, this means the query returned no rows.
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。