简体   繁体   English

如何将java日期类型存储到mysql日期类型?

[英]how to store java date type to mysql date type?

如何将java日期类型存储到mysql日期类型?

See that your Date is a java.sql.Timestamp (especially if you want hours,mins,sec.. to be persisted)看到你的Date是一个java.sql.Timestamp (特别是如果你想要小时,分钟,秒......被持久化)
You could convert a java.util.Date to a Timestamp like so: new Timestamp(date.getTime())您可以将java.util.Date转换为Timestamp如下所示: new Timestamp(date.getTime())

使用Calendar类的一些实例将日期转换为字符串并在 SQL 查询中使用该字符串。

Use a PreparedStatement to execute the SQL statement, like this:使用PreparedStatement执行 SQL 语句,如下所示:

Date date = ...;

PreparedStatement ps = connection.prepareStatement("INSERT INTO mytable (this, that, datecol) values (?, ?, ?)");

ps.setString(1, "hello");
ps.setString(2, "world");
ps.setTimestamp(3, new java.sql.Timestamp(date.getTime()));

ps.executeUpdate();

When you do it like this, you let the JDBC driver convert it to the format that the database expects, so that your program can remain database independent (you don't need to deal with formatting it in the way that MySQL expects it yourself).当你这样做时,你让 JDBC 驱动程序将它转换为数据库期望的格式,这样你的程序就可以保持数据库独立(你不需要按照 MySQL 自己期望的方式处理它的格式化) .

When querying the database, also use PreparedStatement and use the getTimestamp() method on the ResultSet to get the date as a java.sql.Timestamp object.查询数据库时,也使用PreparedStatement并使用ResultSet上的getTimestamp()方法以java.sql.Timestamp对象的ResultSet获取日期。

java.time时间

The modern approach uses java.time classes.现代方法使用java.time类。

The DATE type in MySQL represents a date only, without time of day and without one zone. MySQL 中的DATE类型仅表示日期,没有时间和区域。

So use LocalDate with a driver compliant with JDBC 4.2.因此,将LocalDate与符合 JDBC 4.2 的驱动程序一起使用。

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
LocalDate today = LocalDate.now( z ) ;

myPreparedStatement.setObject( … , today ) ;

Retrieval.恢复。

LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM