Java createNativeQuery Insert datetime

0

I'm trying to do an Insert in a database whose dates are datetime2 (7).

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

Query u = em.createNativeQuery(insert);
u.setParameter(1, sdf );

This is giving the following error

  

Implicit conversion from data type varbinary to date is not allowed. Use the CONVERT function to run this query.

    
asked by anonymous 21.05.2018 / 20:11

1 answer

0

SimpleDateFormat is not a date. This class is used to format dates (transform Date to String ) and do parsing (transform String to Date ) - see a documentation .

If the field in the database is a date, pass Date - java.util.Date , or java.sql.Date (or java.sql.Timestamp , or whatever you are using) to setParameter .

If you have a String and want to save the date, in this case you use SimpleDateFormat to convert String to Date :

Date date = sdf.parse(stringQueContemAData);

And then pass Date to method setParameter :

u.setParameter(1, date);

But since you did not specify which input and output (if it is String , Date , etc), you can not help more than that.

Dates are not formatted, only values (see this article that explains this subtle difference well). Just because you are viewing the date in a specific format does not necessarily mean that it is in that format.

Internally, each language, API, or database writes date types to an internal format, but does not matter to who uses them. When the date is displayed (printed, recorded in a file, shown on the screen, etc.), a display format is chosen. But that does not mean that the date is recorded in that format.

That said, if the field in the database is of type datetime, just pass Date to setParameter .

    
21.05.2018 / 20:23