如何将保存日期和时间的 java.util.Date 对象插入到 mysql 数据库中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22448713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:46:43  来源:igfitidea点击:

How to insert java.util.Date object holding date and time into mysql database

javamysqljdbcjava.util.date

提问by cks

I am using following code to insert a java.util.Dateobject in MySQL. d1is date object I'm getting from a function. I tried casting java.util.Dateinto java.sql.Datebut this doesn't save the time part.

我正在使用以下代码java.util.Date在 MySQL 中插入一个对象。d1是我从函数中获取的日期对象。我试着铸造java.util.Datejava.sql.Date但这并不节省时间的一部分。

String sql = "INSERT INTO abc " +
              "VALUES" + "('Zara',?)";
pstmt = conn.prepareStatement(sql);
pstmt.setDate(1, d1);
stmt.executeUpdate(sql);

Any Idea to store Date and time of Date Object in MySQL?

任何想法在 MySQL 中存储日期对象的日期和时间?

采纳答案by Ravinder Reddy

You need to convert java.util.Dateinstance to java.sql.Dateformat. and then use it with PreparedStatement.

您需要将java.util.Date实例转换为java.sql.Date格式。然后将它与 PreparedStatement 一起使用。

Change:

改变:

pstmt.setDate( 1, d1 );

to:

到:

pstmt.setDate( 1, new java.sql.Date( d1.getTime() );

If the field is of type datetimeor timestamp, you have to use

如果该字段的类型为datetimeor timestamp,则必须使用

pstmt.setTimestamp( 1, new java.sql.Timestamp( d1.getTime() );