如何正确使用setDate?

时间:2011-09-13 14:23:05

标签: java postgresql jdbc getdate

我的表格中包含“日期”列,并以格式输入日期:“2011-09-06” 我想执行查询:

select * from tvprograms where date=?

我试试这个:

Date startDate;
java.util.Date date;
Calendar cal = Calendar.getInstance();
cal.set(2011, 9, 1);
startDate = cal.getTime();
TVProgramDAO tvDAO = new TVProgramDAO();
tvDAO.findUnusedTvPrograms(new java.sql.Date(date.getTime()));

findUnusedTvPrograms看起来:

public List<Integer> findUnusedTvPrograms(Date date) {
    List<Integer> results = new ArrayList<Integer>();
    if (obtainConnection()) {
        PreparedStatement stmt = null;
        ResultSet rs = null;
        ...
            stmt = con.prepareStatement(findOldTvProgQuery.toString());

            stmt.setDate(1, date);
            rs = stmt.executeQuery();

            while (rs.next()) {

                results.add(rs.getInt(1));
             ...
    return results;
}

但它不起作用。

1 个答案:

答案 0 :(得分:2)

此代码无法编译,只要我能看到:

Date startDate;
java.util.Date date;
Calendar cal = Calendar.getInstance();
cal.set(2011, 9, 1);
startDate = cal.getTime();
TVProgramDAO tvDAO = new TVProgramDAO();
tvDAO.findUnusedTvPrograms(new java.sql.Date(date.getTime()));

您正在尝试使用date,但您从未初始化变量。这是一个稍微清洁的版本:

Calendar cal = Calendar.getInstance();
cal.set(2011, 9, 1);
Date startDate = cal.getTime();
TVProgramDAO tvDAO = new TVProgramDAO();
tvDAO.findUnusedTvPrograms(new java.sql.Date(startDate.getTime()));

请注意,这将使用系统的默认时区,这可能不是一个好主意。我个人建议使用Joda Time而不是......