Jury A
Jury A

Reputation: 20052

How to insert current date into MySQL database use Java?

I want to insert the current date and time into a columns defined as datetime type.

I typed the following code:

java.sql.Date sqlDate = new java.sql.Date(new java.util.Date().getTime());
PrepStmt.setDate(1, sqlDate);

When I check the database, I find that the date inserted correctly, but the time is: 00:00:00. What is the fix ?

Upvotes: 17

Views: 55780

Answers (6)

SFDCCoder
SFDCCoder

Reputation: 23

java.sql.Timestamp date = new java.sql.Timestamp(new java.util.Date().getTime());
PrepStmt.setTimestamp(1, date);

I solved it using this..

Upvotes: 2

Rohit Jain
Rohit Jain

Reputation: 213193

Since you are using datetime as your column type, you need to use java.sql.Timestamp to store your date, and PrepareStatement.setTimestamp to insert it.

Try using this: -

java.sql.Timestamp date = new java.sql.Timestamp(new java.util.Date().getTime());
PrepStmt.setTimestamp(1, date);

Upvotes: 29

Jacob
Jacob

Reputation: 14731

Try with setTimestamp as

PrepStmt.setTimestamp(1, sqlDate);

Upvotes: 2

ramsinb
ramsinb

Reputation: 2005

Sounds like you need

java.sql.Timestamp

The one that your using java.sql.Date is for dealing with dates only and does not record time. Alternatively you can use java.sql.Time if you do want time only.

Upvotes: 3

Sujay
Sujay

Reputation: 6783

What you need to use is the setTimestamp(int parameterIndex,Timestamp x) method instead of the setDate() method.

One of the ways you can set the timestamp would be as follows:

Timestamp timestamp = new Timestamp(new Date().getTime());

You can then set the parameter as:

PrepStmt.setTimestamp(1, timestamp);

Upvotes: 4

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

You are using wrong method. You can use PreparedStatement#setTimestamp(int parameterIndex, Timestamp x) instead.

Upvotes: 9

Related Questions