Java 中 PreparedStatement 的解决方法 setDate

Workaround setDate for PreparedStatement in Java

我有一个带有 PreparedStatement 的方法

    public static boolean TSTHolidayPrepMapper(PreparedStatement st, TSTObject item, MapperType type) throws SQLException
{
    TSTHoliday hol = (TSTHoliday) item;
    int id = 1;
    if (type != MapperType.DELETE)
    {
        st.setString(id++, hol.getCountry());
        st.setString(id++, hol.getCommodity());
        st.setString(id++, hol.getMarketArea());
        st.setString(id++, hol.getMarketPlace());
        st.setString(id++, hol.getName());

        st.setDate(id++, hol.getCalenderDate());
    }
    if (type != MapperType.INSERT)
        st.setInt(id++, hol.getId());

    return true;
}

需要 st.setDate(id++, hol.getCalenderDate()) 的 Date 类型对象,但是 getCalenderDate() 方法提供了一个 class 的对象,我自己创建了一个名为 TSTLocalDate

的对象
public class TSTLocalDate extends TSTObject
{
public int year;
public int month;
public int day;

public TSTLocalDate()
{
    this.year = 1900;
    this.month = 1;
    this.day = 1;
}

public TSTLocalDate(int year, int month, int day)
{
    this.year = year;
    this.month = month;
    this.day = day;
}

public String toString()
{
    String val = "" + year + "-" + TSTStringFormatter.getIntWithLeadingZeros(month, 2) + "-" + TSTStringFormatter.getIntWithLeadingZeros(day, 2);

    return val;
}
}

我想过两种不同的解决方案

  1. 我试图将我的 TSTLocalDate calenderDate 转换为 Date calenderDate,但似乎效果不佳,因为 Date classes 方法已弃用

    @SuppressWarnings({ "deprecation"})
    public Date tstlocaldateToDate(TSTLocalDate tstlocaldate) throws ParseException {       
    
    Date date = new Date(0);
    
    date.setYear(tstlocaldate.year);
    date.setMonth(tstlocaldate.month);
    date.setDate(tstlocaldate.day);
    
    Log.info(date.getYear());
    return date;
    }
    
  2. 我试图找到一种方法来为 PreparedStatement 声明自己的数据类型,这样我就可以像 st.setTSTLocalDate(id++, hol.getCalenderDate()); 一样将 calenderDate 作为 TSTLocalDate 对象传递给 PreparedStatement,但遗憾的是我没有找到方法.

我更喜欢第二种解决方案,但我也愿意接受其他解决方案。

...but it seems like it does not work well since the Date classes methods are deprecated.

如果您查看 JavaDoc 的弃用消息,it tells you what to do:

Deprecated.

As of JDK version 1.1, replaced by Calendar.set(Calendar.YEAR, year + 1900).

(我强调的是第二段)

所以旧的方法是:

  • 使用 getInstance 或其重载之一获得 Calendar
  • 使用Calendar的方法设置正确的日期。
  • 使用 bizarrely-named getTime 获取该日期的 Date 实例。
  • 使用java.sql.Date构造器,传入DategetTime().
  • 将其与您的 PreparedStatement 一起使用。

就是说,对于现代 JDK,您可能希望通过 java.time classes, probably LocalDate, to do the conversion instead as it's a fair bit simpler. Then you'd use java.sql.Date.valueOf(LocalDate):

ps.setDate(java.sql.Date.valueOf(LocalDate.of(
    tstlocaldate.year,
    tstlocaldate.month,
    tstlocaldate.dayOfMonth
));