This week's book giveaway is in the Big Data forum.
We're giving away four copies of Elasticsearch in Action and have Radu Gheorghe & Matthew Lee Hinman on-line!
See this thread for details.
The moose likes JDBC and Relational Databases and the fly likes Trying to convert and insert date into mysql Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Elasticsearch in Action this week in the Big Data forum!
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "Trying to convert and insert date into mysql" Watch "Trying to convert and insert date into mysql" New topic
Author

Trying to convert and insert date into mysql

Pranit Sonawane
Ranch Hand

Joined: Jul 29, 2011
Posts: 166

Hi all, I searched many forums and finally all I found is this



but its still showing an exception:- java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Date

Can anybody please help!
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 62123
    
  68

DateFormat.parse() returns a Date, so why are you trying to cast it to what it already is?

Getting rid of superfluous code is a good first step when diagnosing a problem.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 19345
    
  10

If you have a java.util.Date object and you want to convert it to a java.sql.Date object, casting isn't the way to do that. (That's because java.util.Date isn't a subclass of java.sql.Date.) To do the conversion, create a new java.sql.Date object from the java.util.Date object -- check out the available constructors in the API documentation.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 62123
    
  68

That is what is occurring on line 8 and 9.

It's not clear where the exception is coming from, but I suspect cleaning up the code will make it easier to find.

In the future, please be sure to include the line number of the statement that is causing the exception.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 19345
    
  10

The error messages are complaining about casts to java.sql.Date. There are casts to "Date" in the code. A natural inference would be that "import java.sql.Date" was in the part of the code not posted. It wouldn't be hard for somebody with access to all of the code to look and see.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 62123
    
  68

You're a step a ahead. I'm assuming that when the unnecessary casts are removed, that that's what will be revealed.
 
Consider Paul's rocket mass heater.
 
subject: Trying to convert and insert date into mysql