Reputation: 3602
How can I Convert Java Timestamp (Timestamp data type) to MySQL timestamp vice versa?
Upvotes: 1
Views: 7202
Reputation: 206856
If you're using the JDBC API to access the database, and you're using a PreparedStatement
to for example execute an SQL INSERT statement, then you just set the timestamp as a parameter to the PreparedStatement
:
Timestamp ts = ...; // wherever you get this from
PreparedStatement ps = connection.prepareStatement("INSERT INTO MYTABLE (ts) VALUES (?)");
ps.setTimestamp(1, ts);
ps.executeUpdate();
Likewise, when you're doing a query that returns a timestamp, get it from the ResultSet
by calling getTimestamp
on it. Example:
Timestamp result = null;
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery("SELECT ts FROM MYTABLE WHERE ...");
if (rs.next()) {
result = rs.getTimestamp(1);
}
See the JDBC Tutorial.
Upvotes: 5
Reputation: 16235
As far as I can see from MySQL docs, java.sql.Timestamp should just work if you read it from or write it to a TIMESTAMP field in the database. So you should not need to do any conversion.
Upvotes: 1
Reputation: 3240
Without more specifics on the trouble you are having, this will be a hard question to answer. However, Java makes this relatively straightforward if you are using prepared statements. Your code would look something like this:
Connection conn = getConnection();
PreparedStatement pStmt = conn.prepareStatement("UPDATE my_table SET my_column = ? WHERE id = ?");
pStmt.setTimestamp(1, new Timestamp(System.currentTimeMillis()));
pStmt.setInt(2, 42);
pStmt.executeUpdate();
Upvotes: 3