Search code examples
javamysqlresultset

SQL Exception when reading from ResultSet


This is a DAO method that gets called when the user clicks the login button. loginemail and pass are the credentials entered by the user in the form. The column name is Password in the database and the table name is users.

The main problem is that ResultSet is not working as it should, however the prepared statements with 'Insert' SQL query works nicely:

 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;
    }
}

This is the method which registers users. It is working nicely, but when I introduce the ResultSet it gives me lemons.

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;
    }
}

Solution

  • Did a Rookie mistake, replaced if(rs.next()) by while(rs.next()) and it worked