0

So my problem is that I want to allow the user to change the shipping date of the product according to what they want. So what I did is that I collect the year,month and day input from the user and convert it into the date format that SQL required. All the input was fine but whenever I wanted to update the shipping date, it doesn't update and neither shows the error.

I used the input that I got from the user to set the Calendar class's year,month and date. Then I converted the date into the java.util.Date before I could convert it into java.sql.Date

 //sql query
private static final String UPDATESHIPPINGDATE = "UPDATE book SET shippingDate = ? WHERE orderID = ? ";

//Required format for SQL
private static final String DATE_FORMAT_NOW = "yyyy-MM-dd";

Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);

//The method
 public void updateShippingDate(int orderID, int year,int month,int day){
        try(Connection con = DBConnection.getConnection();
            PreparedStatement stmtUpdate = con.prepareStatement(UPDATESHIPPINGDATE);
            PreparedStatement stmtShippingDate = con.prepareStatement(GETSHIPPGINGDATE);
            ){

            cal.set(Calendar.YEAR,year);
            cal.set(Calendar.MONTH,(month-1));
            cal.set(Calendar.DATE,(day-1));

            Date dateConvert = cal.getTime();
            java.sql.Date shippingDate = new java.sql.Date(dateConvert.getTime());

            stmtUpdate.setInt(1,orderID);
            stmtUpdate.setDate(2,shippingDate);

            stmtUpdate.executeUpdate();

            stmtShippingDate.setInt(1,orderID);
            ResultSet result = stmtShippingDate.executeQuery();

            while (result.next()){
                System.out.println("Your new shipping date: " + result.getDate("shippingDate"));
            }

        }catch (Exception e){
            System.out.println(e);
        }
    }

Expected: 2019-06-20(updated output) The output was: 2019-06-24(old output)

ConcealedREPO
  • 31
  • 1
  • 6
  • 2
    You have mixed up your parameter indexes. The first parameter is the date and the second parameter is the order id. Your code has it the other way around. – Mark Rotteveel Jun 18 '19 at 04:55
  • 2
    As a side note, I suggest that you use `LocalDate` which is available since Java 8 instead of `Calendar`. You could simply do `java.sql.Date shippingDate = java.sql.Date.valueOf(LocalDate.of(year, month, day));` – THe_strOX Jun 18 '19 at 05:10
  • @THe_strOX That's already an improvement. Still better is `stmtUpdate.setObject(1, LocalDate.of(year, month, day));`. We don't need the outdated `java.sql.Date` at all. – Ole V.V. Jun 18 '19 at 07:11
  • Much more information [in this question: Getting the date from a ResultSet for use with java.time classes](https://stackoverflow.com/questions/29773390/getting-the-date-from-a-resultset-for-use-with-java-time-classes) – Ole V.V. Jun 18 '19 at 11:53

0 Answers0