抛出异常结果集已关闭

时间:2015-12-29 17:17:44

标签: java jdbc

它是一种登录形式  这个代码抛出异常结果集是关闭的......为什么rs不包含表? 在我添加<<之前String rsusername = rs.getString(" name");                     String rspassword = rs.getString(" password");>> 始终打印worng用户名或密码

我该如何解决?

* preparedstatement对代码没有影响

代码:

final JButton btnNewButton = new JButton("Log in");
    btnNewButton.addActionListener(new ActionListener() {
        @SuppressWarnings("deprecation")
        public void actionPerformed(ActionEvent arg0) {

            String password=passwordField.getPassword().toString();
            String UserName = textField_1.getText().toString();
            try
            {
                Class.forName("org.sqlite.JDBC");   
                Connection con=DriverManager.getConnection("jdbc:sqlite:C:\\Users\\max\\Desktop\\javaproject\\hotel");
                String sqlcheck="select * from login where  login.Name ='"+UserName+"'and login.password='"+password+"'";
                Statement s =con.createStatement();
                ResultSet rs=s.executeQuery(sqlcheck);
                String rsusername=rs.getString("name");
                String rspassword=rs.getString("password");

                if(rs.next())
                {

                btnNewButton.addMouseListener(new MouseAdapter() {
                    @Override
                        public void mouseClicked(MouseEvent arg0) {
                            Hotel1 hotel=new Hotel1();
                            hotel.setVisible(true);
                }
            });

                }
                 else
                   JOptionPane.showMessageDialog(null, "worng user name or password");
            }
            catch(ClassNotFoundException | SQLException e)
            {
                JOptionPane.showMessageDialog(null, "class not found exception"+e);
            }

1 个答案:

答案 0 :(得分:1)

您需要将调用升级到rs.next,如下所示:

if (rs.next ()) { 
   String rsusername=rs.getString("name"); 
   String rspassword=rs.getString("password"); 

试试这样:

    String sqlcheck=
             "select * from login where"
             + " login.Name = ?  and login.password=? ";
    try(PreparedStatement s =con.prepareStatement(sqlcheck)) {
      s.setString(1 , UserName);
      s.setString(2, password);
      try(ResultSet rs=s.executeQuery()) {
          if(rs.next()) {
            String rsusername=rs.getString("name");
            String rspassword=rs.getString("password");
            btnNewButton.addMouseListener(new MouseAdapter() {
              @Override
                  public void mouseClicked(MouseEvent arg0) {
                      Hotel1 hotel=new Hotel1();
                      hotel.setVisible(true);
                  }
             });
          } else {
             JOptionPane.showMessageDialog(null, "worng user name or password");
          }
      }
    } catch(ClassNotFoundException | SQLException e) {
        JOptionPane.showMessageDialog(null, "class not found exception"+e);
    }