Using setDate in PreparedStatement

后端 未结 6 1646
我在风中等你
我在风中等你 2020-11-22 12:35

In order to make our code more standard, we were asked to change all the places where we hardcoded our SQL variables to prepared statements and bind the variables instead. <

6条回答
  •  臣服心动
    2020-11-22 13:02

    The problem you're having is that you're passing incompatible formats from a formatted java.util.Date to construct an instance of java.sql.Date, which don't behave in the same way when using valueOf() since they use different formats.

    I also can see that you're aiming to persist hours and minutes, and I think that you'd better change the data type to java.sql.Timestamp, which supports hours and minutes, along with changing your database field to DATETIME or similar (depending on your database vendor).

    Anyways, if you want to change from java.util.Date to java.sql.Date, I suggest to use

    java.util.Date date = Calendar.getInstance().getTime();
    java.sql.Date sqlDate = new java.sql.Date(date.getTime()); 
    // ... more code here
    prs.setDate(sqlDate);
    

提交回复
热议问题