[英]Convert Java Timestamp to MySQL timestamp vice versa
如何将Java时间戳(时间戳数据类型)转换为MySQL时间戳,反之亦然?
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
: 如果您正在使用JDBC API访问数据库,并且正在使用
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();
Likewise, when you're doing a query that returns a timestamp, get it from the ResultSet
by calling getTimestamp
on it. 同样,当您执行返回时间戳的查询时,可以通过调用
getTimestamp
从ResultSet
它。 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 . 请参阅《 JDBC教程》 。
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.
但是,如果您使用准备好的语句,则Java使此操作相对简单。 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();
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. 据我从MySQL文档所看到的,如果您从数据库中的TIMESTAMP字段读取或将其写入数据库,则java.sql.Timestamp应该可以正常工作。 So you should not need to do any conversion.
因此,您无需进行任何转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.