1

I'm trying to save a timestamp to a table in mySQL but whenever I look at the results it just shows 0000-00-00 00:00:00.

I assume I'm not using the timestamp right but anyways in my table I have a column named time and its property is TIMESTAMP

In my Java I have:

java.sql.Timestamp timestamp = new java.sql.Timestamp(0);

String query = "insert ignore into time(time_now) values (?)";

pstmt.setString(1, timestamp);
pstmt.executeUpdate();

My database connection is fine as I have a lot of other information that's being uploaded to it with no problem, I'm just having trouble with the timestamp

7
  • Firsr you should use datetime instead and second - what is the format of the date you want to insert? It should be yyyy-MM-dd HH:mm:ss Commented Mar 18, 2015 at 23:07
  • Well essentially I need just hh:mm:ss but TIMESTAMP in mysql forces date. If there's a better way to save just time I'd appreciate it. Commented Mar 18, 2015 at 23:09
  • 1
    Yes, the time data type Commented Mar 18, 2015 at 23:12
  • I would still insert into it the same way, with Timestamp? Commented Mar 18, 2015 at 23:14
  • 1
    You can use CURTIME() instead Commented Mar 18, 2015 at 23:15

3 Answers 3

1

Something like this should work:

java.util.Date date = new java.util.Date();
Timestamp timestamp = new Timestamp(date.getTime());
preparedStatement = connection.prepareStatement("insert ignore into time(time_now) values (?)");
preparedStatement.setTimestamp(1, timestamp);
Sign up to request clarification or add additional context in comments.

Comments

1

If you only want to store the time then use the TIME data type instead and to insert the current time of the SQL server use CURTIME() like this

 insert into your_table (time_column) 
 values (curtime())

Comments

0

Take a look at java.sql.Timestamp. You are instantiating a new Timestamp object with '0'.

2 Comments

I tried adding the ints but it Eclipse would not accept it, only 0 passed without errors so I must be doing something else wrong.
It takes a long not an int in the constructor (Note: not a Long object type).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.