How to insert java.util.Date object holding date and time into mysql database [duplicate]

StackOverflow https://stackoverflow.com/questions/22448713

Pergunta

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?

Foi útil?

Solução

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() );
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top