문제

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?

도움이 되었습니까?

해결책

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() );
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top