如何将保存日期和时间的 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
How to insert java.util.Date object holding date and time into mysql database
提问by cks
I am using following code to insert a java.util.Date
object in MySQL. d1
is date object I'm getting from a function. I tried casting java.util.Date
into java.sql.Date
but this doesn't save the time part.
我正在使用以下代码java.util.Date
在 MySQL 中插入一个对象。d1
是我从函数中获取的日期对象。我试着铸造java.util.Date
成java.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.Date
instance to java.sql.Date
format. 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 datetime
or timestamp
, you have to use
如果该字段的类型为datetime
or timestamp
,则必须使用
pstmt.setTimestamp( 1, new java.sql.Timestamp( d1.getTime() );