我想做的是:
接受用户名(uname)和密码(passw)作为用户的输入。
使用
ResultSet
,检索数据库中的用户名和用户给定的用户名匹配的唯一元组。该元组将包含用户名和密码。如果用户提供的密码与数据库中的密码相符,则显示两个凭据都正确的消息,否则其中一个是错误的。
除一种情况外,一切正常。当用户名本身错误时,mysql将根本找不到该属性,并会报错: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
有什么方法可以同时执行这两个操作(在关闭与数据库的连接之前)?如果没有,替代方法是什么?
最佳答案
你应该使用 rs.next()
的结果:
if (rs.next()) {
n=rs.getString("id");
m=rs.getString("pass");
}
如果 rs.next()
返回 false,这意味着查询没有返回任何行。
关于验证时出现 java.sql.SQLException : Illegal operation on empty result set.,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27058791/