java.sql.SQLException:对空结果集的非法操作。在验证时 [英] java.sql.SQLException: Illegal operation on empty result set. when authenticating
问题描述
我要做的是:
-
接受用户名(uname)和密码(passw)作为输入来自用户。
Accept username(uname) and password(passw) as an input from the user.
使用 ResultSet
,检索唯一的元组,数据库中的用户名和用户提供的用户名套装。此元组将包含用户名和密码。
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.
如果用户提供的密码也适合数据库中的密码,则显示两个creadentials正确的消息否则其中一个是错的。
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.
除一例外,一切正常。当用户名本身错误时,mysql根本找不到该属性,并且会给出以下错误: java.sql.SQLException:对空结果集的非法操作。
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.
代码是:
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?
推荐答案
你应该使用 rs.next的结果()
:
if (rs.next()) {
n=rs.getString("id");
m=rs.getString("pass");
}
如果 rs.next()
返回false,这表示查询没有返回任何行。
If rs.next()
returns false, this means the query returned no rows.
这篇关于java.sql.SQLException:对空结果集的非法操作。在验证时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!