Frage

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?

War es hilfreich?

Lösung

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() );
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top