【发布时间】:2015-10-19 19:18:34
【问题描述】:
我想做的是:
接受用户名(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
有什么方法可以同时进行这两项操作(在关闭与数据库的连接之前)?如果不是,有什么替代方法?
【问题讨论】: