Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert current date into MySQL database use Java?

Tags:

java

mysql

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 ?

like image 803
Jury A Avatar asked Oct 28 '12 20:10

Jury A


People also ask

How do I get current date in SQL Java?

In order to get "the current date" (as in today's date), you can use LocalDate. now() and pass that into the java. sql. Date method valueOf(LocalDate) .

How can I get current date in database?

INSERT INTO yourTableName(yourDateColumnName) VALUES(NOW()); If your column has datatype date then NOW() function inserts only current date, not time and MySQL will give a warning. To remove the warning, you can use CURDATE().

How do I insert the current date in a column in SQL?

To insert only date value, use curdate() in MySQL. With that, if you want to get the entire datetime, then you can use now() method. Insert both date and time with the help of now().


1 Answers

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);
like image 194
Rohit Jain Avatar answered Oct 05 '22 18:10

Rohit Jain