julia
julia

Reputation: 43

check whether date exists in database

I want to check if the entered date is taken or not.

I tried to fix it but it always indicates that a date has been taken even if it hasn't.

This is the DAO

public static String getDate(String date) throws SQLException, ClassNotFoundException {
    Connection cnx;
    String datee;
    cnx = Connect.getConnection();

    String req = "select date from examen where date=?";
    PreparedStatement st = cnx.prepareStatement(req);
    st.setString(1, date);
    ResultSet rs = st.executeQuery();
    if (rs.next()) {
        String laDate = rs.getString(date);

    }
    return date;

}

and this is the servlet

String dd = ExamDAO.getDate(date);

if (dd != null) {
                        String datePrise = "la date est prise ";
                        request.getSession().setAttribute("datePrise", datePrise);
                        System.out.println("priiiiise ");
                        response.sendRedirect("examen.jsp");
                    } else {...}

Upvotes: 0

Views: 735

Answers (2)

Jasper Huzen
Jasper Huzen

Reputation: 1573

You always return the same date as passed into the method. laDate isn't used so your method doesn't have any working logic in it.

Could be something like:

\\ I suggest a better query with another name for the 'date' column (needs db change), because using column 
\\ names like date can cause problems (reserved keywords/functions in some databases)
"select registrationdate from examen where registrationdate = ?"
String returnDate = inputDate; // inputDate = date argument from method with better name
ResultSet rs = st.executeQuery();
if (rs.next()) {
   returnDate = rs.getString("registrationdate");
}
return returnDate;

or

Optional<String> returnValue = Optional.empty();
ResultSet rs = st.executeQuery();
if (rs.next()) {
   returnValue = Optional.of(rs.getString("registrationdate"));
}
return returnValue;

Upvotes: 2

Sabir Khan
Sabir Khan

Reputation: 10142

I guess, your method is to be rewritten like below if examen.jsp path is for dates already taken. Notice the extra declaration - String laDate =null; & change in return statement.

Also, notice change in laDate = rs.getString("date"); , your need to extract by column name & not variable. Table column name is "date" while date is a variable carrying date values & not table column name.

Variable String datee; from your code is unused, you can remove that.

public static String getDate(String date) throws SQLException, ClassNotFoundException {
    Connection cnx;
    String laDate =null;
    String datee;
    cnx = Connect.getConnection();
    String req = "select date from examen where date=?";
    PreparedStatement st = cnx.prepareStatement(req);
    st.setString(1, date);
    ResultSet rs = st.executeQuery();
    if (rs.next()) {
         laDate = rs.getString("date");

    }
    return laDate ;
}

Upvotes: 0

Related Questions