Java sql - 如何将时间戳插入 mysql 数据库,包括毫秒
Java sql - How to insert TimeStamp into a mysql database including milliseconds
如何将 Java TimeStamp 对象转换为包含毫秒的 SQL 日期时间类型?
当我将 TimeStamp obj 插入数据库时,毫秒数消失了。
这是我的 Java 将字符串转换为时间戳对象的源代码:
import java.sql.Timestamp;
...
...
String timeStr = "2013-08-30 19:11:49.113";
Timestamp timeCreated = Timestamp.valueOf(timeStr);
timeCreated.toString(); //returns "2013-08-30 19:11:49.113"
我在 SQL 中的 table 定义:
CREATE TABLE `Event` (EventTimeStamp datetime NOT NULL);
这是我将 TimeStamp 对象插入数据库的方式:
PreparedStatement psInsert;
Connection conn = ...
psInsert = conn
.prepareStatement("INSERT INTO `Event` (EventTimeStamp) VALUES(?)");
psInsert.setTimestamp(1, timeCreated);
psInsert.executeUpdate();
插入后时间戳被切断,不再有毫秒数:
2013-08-30 19:11:49
感谢
您的数据库列 datetime
没有毫秒的位置。您应该改用 datetime(3)
。
如何将 Java TimeStamp 对象转换为包含毫秒的 SQL 日期时间类型? 当我将 TimeStamp obj 插入数据库时,毫秒数消失了。
这是我的 Java 将字符串转换为时间戳对象的源代码:
import java.sql.Timestamp;
...
...
String timeStr = "2013-08-30 19:11:49.113";
Timestamp timeCreated = Timestamp.valueOf(timeStr);
timeCreated.toString(); //returns "2013-08-30 19:11:49.113"
我在 SQL 中的 table 定义:
CREATE TABLE `Event` (EventTimeStamp datetime NOT NULL);
这是我将 TimeStamp 对象插入数据库的方式:
PreparedStatement psInsert;
Connection conn = ...
psInsert = conn
.prepareStatement("INSERT INTO `Event` (EventTimeStamp) VALUES(?)");
psInsert.setTimestamp(1, timeCreated);
psInsert.executeUpdate();
插入后时间戳被切断,不再有毫秒数:
2013-08-30 19:11:49
感谢
您的数据库列 datetime
没有毫秒的位置。您应该改用 datetime(3)
。