Haritha R
Haritha R

Reputation: 105

How to update MySQL timestamp column using PreparedStatement in Java?

I have created a table as below:

create table sample(id int not null,created_at timestamp,updated_at timestamp,name varchar(100),primary key(id));

I have tried to update the column in different ways as below, but am not able to update the time:

Calendar calender = Calendar.getInstance();
java.util.Date now = calender.getTime();
java.sql.Timestamp updatedAt = new java.sql.Timestamp(now.getTime());
stmt.setTimestamp(2, updatedAt);

java.sql.Timestamp  updatedAt = new java.sql.Timestamp(new java.util.Date().getTime());
stmt.setTimestamp(2, updatedAt);
    
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String updatedAt =sdf.format(date);
stmt.setString(2, updatedAt);

final java.util.Date updatedAt = new java.util.Date(System.currentTimeMillis());
stmt.setDate(2, new java.sql.Date(updatedAt.getTime()));

Please, help me to resolve this issue?

Upvotes: 1

Views: 3958

Answers (1)

Roman C
Roman C

Reputation: 1

The java.sql.Date() strips time portion of your date due to SQL convention. You can check SQL-92 standard.

Timestamp updatedAt = new Timestamp(Calendar.getInstance().getTimeInMillis());
stmt.setTimestamp(2, updatedAt);

Upvotes: 2

Related Questions