开发者

JDBC Bad format for DATE

开发者 https://www.devze.com 2023-03-07 20:16 出处:网络
I am trying to read several dates from my database but under certain circumstances I get a \' java.sql.SQLException Bad format for DATE\'. Here is my code :

I am trying to read several dates from my database but under certain circumstances I get a ' java.sql.SQLException Bad format for DATE'. Here is my code :

Date entryDateD = res.getDate("entryDate");

In debug mode I see that the content of entryDateD '1996-9-15' as is in my database.. Although I would have to mention that I read other dates too from my database which I notice are of the format 'xxxx-0y-zz'. What I want to say is that in case of a m开发者_运维百科onth being less than 10 there is a zero added in front of it which in this case is not added. I suspect that this might have something to do with it. (this zero does not appear in the database itself though not only in this date but in any date) thanx in advance :)


Just a guess, but what MySQL column type do you have for entryDate??

By default a date type in MySQL will generate an yyyy-mm--dd format; the missing zero leads me to believe that the column type may be varchar or other non-date type at DB level.

This could be the cause of your problems at Java level...


If you represent it as java.util.Date, you have the advantage of allowing the JDBC driver to worry about handling any format issues with the database.

As for how it's rendered in your display, that's up to you and your use of the java.text.DateFormat class.

You're doing the right thing by representing a date as java.util.Date in your app, but you need to understand that formatting is a separate issue from the type.


Java has a child class of java.util.Date, called java.sql.Date

The easiest way to create a Java SQL Date is by calling the constructor with a Utility Date.

java.util.Date uDate = res.getDate("entryDate");
java.sql.Date sDate  = new java.sql.Date(uDate.getTime());


If you want to get res.getDate("entryDate") as YYYY-MM-DD then you need to cast as date in your query like this:

SELECT
...
CAST(entryDate as DATE)as entryDate,
...
FROM your_table;

If you feel this is helpful then do upVote to make it useful for others.

0

精彩评论

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

关注公众号