Java: Insert into a table datetime data
According to the error description, you are inserting an incorrect type into the database. See JDBC to MSSQL. You should convert Calendar to Timestamp.
Try using:
PrepareStatement statement = connection.prepareStatement("INSERT INTO Companies CreatedOn VALUES(?)");java.sql.Timestamp timestamp = new java.sql.Timestamp(cal.getTimeInMillis());statement.setTimestamp(1, timstamp);int insertedRecordsCount = statement.executeUpdate();
First of all, do NOT use string concatenation. Have you ever heart about SQL injection?
Correct way how to do that is to use prepared statement:
Idea is you define statement with placeholders and than you define value for those placeholders.
See @Taky's answer for more details.
dateFormat#format
this method returns formatted string not Date
object. Database field is DateTime
and it is expecting java.sql.Timestamp
to be inserted there not String
according to docs.
To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.
Try java.sql.Timestamp
object instead of String in query and I'd recommend you to use PreparedStatement
.