0

I am using following code to insert a java.util.Date object in MySQL. d1 is date object I'm getting from a function. I tried casting java.util.Date into java.sql.Date but this doesn't save the time part.

String sql = "INSERT INTO abc " +
              "VALUES" + "('Zara',?)";
pstmt = conn.prepareStatement(sql);
pstmt.setDate(1, d1);
stmt.executeUpdate(sql);

Any Idea to store Date and time of Date Object in MySQL?

Sully
  • 14,672
  • 5
  • 54
  • 79
cks
  • 83
  • 1
  • 2
  • 9

1 Answers1

5

You need to convert java.util.Date instance to java.sql.Date format. and then use it with PreparedStatement.

Change:

pstmt.setDate( 1, d1 );

to:

pstmt.setDate( 1, new java.sql.Date( d1.getTime() );

If the field is of type datetime or timestamp, you have to use

pstmt.setTimestamp( 1, new java.sql.Timestamp( d1.getTime() );
Ravinder Reddy
  • 23,692
  • 6
  • 52
  • 82