当前位置:   article > 正文

java 非法操作异常,java.sql.SQLException:对空结果集的非法操作。在验证时

java.sql.sqlexception: illegal operation on empty result set.

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.

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/252740
推荐阅读
相关标签
  

闽ICP备14008679号