将Java时间戳转换为MySQL时间戳,反之亦然

bbn*_*bnn 1 java time timestamp date

如何将Java时间戳(时间戳数据类型)转换为MySQL时间戳,反之亦然?

Jes*_*per 5

如果您正在使用JDBC API访问数据库,并且您正在使用a PreparedStatement来执行SQL INSERT语句,那么您只需将时间戳设置为以下参数PreparedStatement:

Timestamp ts = ...; // wherever you get this from

PreparedStatement ps = connection.prepareStatement("INSERT INTO MYTABLE (ts) VALUES (?)");
ps.setTimestamp(1, ts);
ps.executeUpdate();
Run Code Online (Sandbox Code Playgroud)

同样,当您执行返回时间戳的查询时,请ResultSet通过调用它来获取getTimestamp它.例:

Timestamp result = null;

Statement st = connection.createStatement();
ResultSet rs = st.executeQuery("SELECT ts FROM MYTABLE WHERE ...");
if (rs.next()) {
    result = rs.getTimestamp(1);
}
Run Code Online (Sandbox Code Playgroud)

请参阅JDBC教程.