SQL 从 ResultSet 读取时出现异常

SQL Exception when reading from ResultSet

这是一个在用户单击登录按钮时调用的 DAO 方法。 loginemailpass 是用户在表单中输入的凭据。 数据库中的列名称为 Password,table 名称为 users.

主要问题是 ResultSet 没有正常工作,但是带有 'Insert' SQL 查询的准备好的语句工作得很好:

 public String authorize(String loginemail,String pass){
        Connection conn=null;
        boolean correctPassword=false;
        String pwd="default";
        PreparedStatement st=null;
    try{
        Class.forName("com.mysql.jdbc.Driver");
        conn=DriverManager.getConnection(DB_URI,DB_USERNAME,DB_USERNAME);
        st=conn.prepareStatement("SELECT Password FROM users WHERE Email = ?");
        st.setString(1,loginemail);

        ResultSet rs=st.executeQuery();


        if(rs.next())
        pwd=rs.getString("Password");    //(SQLException)error in this line
    }

    catch(SQLException se){
        se.printStackTrace();
    }
    catch(Exception e){
        e.printStackTrace();
    }
    finally{
        return pwd;
    }
}

这是注册用户的方法。它工作得很好,但是当我引入 ResultSet 时,它让我很吃惊。

public class UserDAO{
    static final  String DB_URI="jdbc:mysql://localhost:3306/social";
    static final String DB_USERNAME="root";
}
public boolean createUser(User user){

    Connection conn=null;
    boolean allGood=false;
    try{
        Class.forName("com.mysql.jdbc.Driver");
        conn=DriverManager.getConnection(DB_URI,DB_USERNAME,DB_USERNAME);
        PreparedStatement ps=null;
        String userQ="INSERT INTO users (Name,Email,Gender,Password) VALUES (?,?,?,?)";
        ps=conn.prepareStatement(userQ);
        ps.setString(1,user.getName());
        ps.setString(2,user.getEmailId());
        ps.setString(3,user.getGender());
        ps.setString(4,user.getPassword());

        ps.execute();
        conn.close();
        ps.close();
        allGood=true;
    }
    catch(SQLException se){
        se.printStackTrace();
    }
    catch(Exception e){
        e.printStackTrace();
    }
    finally{
        return allGood;
    }
}

从 String pwd 中删除 "default" 并试试这个。

String pwd="";

希望这有效!!

犯了新手错误,用 while(rs.next()) 替换了 if(rs.next()) 并且成功了