Search code examples
javasqldatetimesqldatetime

Insert datetime to database


Date currentDateTime;
java.sql.Date sql_currentDateTime;
currentDateTime = getCurrentDateTime(); //Fri Jun 21 15:53:59 AZST 2013
sql_currentDateTime = new java.sql.Date(currentDateTime.getTime()); //2013-06-21

PreparedStatement insertStmt = null;
sqlToMessage = "insert into message values (?)";
insertStmt = conn.prepareStatement(sqlToMessage);
insertStmt.setDate(1, sql_currentDateTime);
insertStmt.executeUpdate();

I want to insert current date time (20-Jun-13 16:04:32) into database. But data inserted to database like that 20-Jun-13, not like 20-Jun-13 16:04:32. How to solve it ? thank u


Solution

  • You need to use java.sql.Timestamp instead of java.sql.Date.

    The java.sql.Timestamp has the date and the time. Have a look at the docs.

    Also, it is important that the column of the table is of type Timestamp.