2

I have a variable of type Date. I get this date by using a function that return type Date. So, I defined two variables as:

Date expDate=null, startDate=null;

Then, I called the functions:

expDate=c.getNotAfter();
startDate= c.getNotBefore();

Then, inserted into the database using:

prepStmt.setDate(1,(java.sql.Date) startDate);
prepStmt.setDate(2, (java.sql.Date) expDate);

After running the program, I get this error:

java.util.Date cannot be cast to java.sql.Date

The columns in the database are defined as DATETIME type. How can I resolve the issue?

0

3 Answers 3

3

Do like this:

  prepStmt.setDate(1,new java.sql.Date(startDate.getTime()));

java.sql.Date is a thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE value. A milliseconds value represents the number of milliseconds that have passed since January 1, 1970 00:00:00.000 GMT.

java.util.Date classes getTime() returns the time in miliseconds. You can use this to create a new object of java.sql.Date class.

If you want time along with date, then use Timestamp:

prepStmt.setTimestamp(1,new java.sql.Timestamp(startDate.getTime()));
Sign up to request clarification or add additional context in comments.

3 Comments

The problem here is that the date s inserted correctly, but the time inserted in the DB as: 00:00:00.
the you have to use setTimestamp() as java.sql.Date discards the time part
the values that is being stored in the database is in format 10-May-16 12:00:00 AM, I want it to be stored in the format 10-May-16 what can be done.?
3

Use it like this:

prepStmt.setDate(1,new java.sql.Date(startDate.getTime())); 

This is because setDate() method of PreparedStatement requires an object of java.sql.Date type as second argument and not java.util.Date.

So first get the time in milliseconds from your java.util.Date object and then use that in the constructor of java.sql.Date.

Comments

1
prepStmt.setDate(1, (java.sql.Date) startDate);   
prepStmt.setDate(2, (java.sql.Date) expDate);  
prepStmt.setDate(1, new java.sql.Date(startDate.getTime()));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.