Java.sql 中的 datetime 等价物? (有 java.sql.datetime 吗?)

到目前为止,我还没有找到一个明确的答案。

我想知道,使用 PreparedStatement,SQL 类型 DATETIME 和 Java 类型的等价物是什么。

我发现: http://www.java2s.com/Code/Java/Database-SQL-JDBC/StandardSQLDataTypeswithTheirJavaEquivalents.htm

但是它声明 SQL 类型“ DATETIME”与 SQL.date 相同,但是当查看 SQL 日期文档(http://download.oracle.com/javase/7/docs/api/java/sql/Date.html)时,它说时间被截断(全部为零)。

我想要的是能够指定一个 preparedStatement.setDateTime()或某种排序。

我看到的唯一其他方法是使用时间戳,但是这将需要我更改列类型,而我无法想象其他人以前从未遇到过这个问题?

有线索吗?

编辑: 我正在使用 MYSQL。

116635 次浏览

The equivalent of MS SQL Server or MySQL DATETIME data type or Oracle DATE data type is java.sql.Timestamp.

The java.sql package has three date/time types:

You want the last one: java.sql.Timestamp.

If you are using these types, you don't need to call a specific setter; just use:

java.util.Date date = new Date();
Object param = new java.sql.Timestamp(date.getTime());
// The JDBC driver knows what to do with a java.sql type:
preparedStatement.setObject(param);

I had a similar problem with my Mysql having SQL date and locally in my app i only had Date

I solved like this

java.sql.Date dataStartSql = new java.sql.Date(start.getTime());

After that used the setDate normally, and I used a getTimestamp to retrive the first value.

where start is a Date object.

In Java we have java.util.Date to handle both Date and Time values.

In SQL, you have commonly Dates (only dates), Time (only time) and DateTime/Timestamp (date and time).

In your Java program, usually you'll always have java.util.Date, so each time you're setting Dates/Times/DateTimes in PreparedStatements, always choose exactly which one you need, according to the database.