开发者

Java method halts when retrieving java.sql.Date object from mysql database, why?

My java class (servlet) has been running fine, but recently, I noticed a problem.

In my database, I have a Date column called 'Full_Expiration_Date'. If one was entered it will store it like '2010-11-17'. If one wasn't entered, is stores it like '0000-00-00'.

In my class, I call the records from the db, and look at the 'Full_Expiration_Date' field to see if it has a date or not. If it does, I execute a few lines of code that check to see if before today's date, and if the date is NOT today's date - if both those conditions are met, the coupon has expired.

So my code works just fine when there IS an expiration date specified, but fails when '0000-00-00' is in the field.

I'm generating an array of information for each coupon in the db table. Once the checking is complete and the array is filled, its sent as a request attribute.

Here's a snippet of my code for this process -

rs = stmt.executeQuery("select Full_Expiration_Date from coupons");

//will hold value from "Full_Expiration_Date" field in db
java.sql.Date expirationDate = null;

//today's date - used for comparison
java.util.Date today = new java.util.Date()开发者_JAVA技巧;  

while(rs.next()) {
    //get expiration date from db for this record
    expirationDate = rs.getDate(12);  

    if(expirationDate == null) { //should be if the field is 0000-00-00, right?
       //don't do any checking against
       //expiration date, this record 
       //doesn't have one
       couponList[counter][11] = "";
     } else { //10                         
       if(expirationDate.before(today) & !today.equals(expirationDate)) { 
          couponList[counter][11] = "expired";
           } else { //11
          couponList[counter][11] = "";
       }//if 
     }//if
   counter++;
  }//while   

Can someone pinpoint what I'm doing wrong here? I'm certain, after testing, that it has to do with the field being 0000-00-00.


0000-00-00 is an invalid date that can't be parsed by Java. You need to allow nulls in that field so that MySQL will stop inserting 0s and that way your if(expirationDate == null) check will actually work.

This is stupid behavior IMO and you should "fix it" by turning on Strict mode. http://dev.mysql.com/doc/refman/5.1/en/server-sql-mode.html#sqlmode_no_zero_date


You can work around this using MySQL's "zeroDateTimeBehavior" configuration property. In your connection properties set:

"zeroDateTimeBehavior" to "convertToNull"

Anytime a 0000-00-00 date is retrieved, it will return null instead of throwing an exception.

Reference: http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-configuration-properties.html

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜