English 中文(简体)
日间java时间
原标题:Datetime in java
  • 时间:2012-05-25 10:21:10
  •  标签:
  • java
  • jdbc

我有一个 JDBC 的当前“ 强” 日期和时间 < / 强” 插入 Mysql 数据库 。

它向 Mysql 日期类型字段提交当前日期和固定时间为 < code> 2012/ 05/ 25 00: 00/ 00: 00 。 日期部分工作非常顺利, 但时间没有显示任何值 。

Im 用以下代码插入值 :

java.util.Date myDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(myDate.getTime());
PreparedStatement PStmt = con.prepareStatement(Sql query);
PStmt.setDate(1,sqlDate);
最佳回答

(1) 在你的java类中使用java. util.Date

(2) 在 Mysql 中设置数据tye TIMESTAMP

Date CreatedDate= new Date(System.currentTimeMillis());

写作声明:可能是这样的:

PreparedStatement PStmt = con.prepareStatement(Sql query);
PStmt.setDate(1,CreatedDate);
问题回答

使用 java.sql.Timestamp 而不是 java.util.Date

例如,如果您正在使用 preparatement 处理您的插入,您可以以下列方式通过日期:

java.util.Date date = new Date();
pst.setTimestamp(columIndex, new java.sql.Timestamp(date.getTime()));

我认为你需要把时间戳 印成在 Mysql 的专栏类型。

我建议注意 java.util.Date java.sql.Date 之间的区别。

java.util.Date vs java.sql.Date

<强度 > EDIT 也确保数据库中有适当的数据类型(DATE、DATETIME或TimeSTAMP)

http://dev.mysql.com/doc/refman/5.1/en/datetime.html

答案很简单, 取决于您的需求- 依您的需求使用 DATETIME 数据类型, 并使用以下数据类型

java.util.Date date = new Date();
pst.setTimestamp(columIndex, new java.sql.Timestamp(date.getTime()).getTime());

让我们从数据库和jdbc的侧面看推理。

从数据库中的数据类型开始, 并选择合适的数据类型。 适合您的情况是 DATETIME 。 DATETIME 类型用于存储壁钟时间, 而 NATIME 类型则用于固定时间点( 时间点后为几毫秒 ) 。 在 MySQL 中, 两者的内部存储方式也有所不同 。

当您来到 JDBC 一侧时, 您有 API 方法, 包括日期( 只有日期部分)、 时间标记( 日期和时间) 和时间( 只有时间时间) 。 这就是 JDBC 所能提供的全部。 所以现在, 适合您需要的 API 设置为Timestamp 。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签