开发者

How to correctly use setDate?

开发者 https://www.devze.com 2023-04-04 08:46 出处:网络
I have table with column \"date\" and type Date in format: \"2011-09-06\" and i want to execute query:

I have table with column "date" and type Date in format: "2011-09-06" and i want to execute query:

select * from tvprograms where date=?

And I try this:

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 looks:

public List<Integer> findUnusedTvPrograms(D开发者_高级运维ate 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;
}

But it doesnt work.


This code won't compile to start with as far as I can see:

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()));

You're trying to use date but you've never initialized the variable. Here's a slightly cleaner version:

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()));

Note that that will use the default time zone of the system, which may not be a good idea. Personally I would recommend using Joda Time instead...

0

精彩评论

暂无评论...
验证码 换一张
取 消