如何从sql数据库获取日期数据类型到java?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22784523/
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 17:52:06  来源:igfitidea点击:

How to get date datatype from sql database to java?

javadateuser-interfacedatetimepicker

提问by Clean code

How to get the date datattype from sql database to java??? so far I have use this code but failed to fetch the date.

如何从sql数据库获取日期数据类型到java???到目前为止,我已使用此代码但未能获取日期。

import java.sql.*;//this is my import file
     String search="select * from tblflight";//select all data from my table
     ResultSet rs=stmt.executeQuery(search);//puting result in temporary var
     while(rs.next())
{
   Date d_time=rs.getDate("date_time");//getting result
   combo_box.addItem(d_time);//n showing error here while putting the date var here
}

采纳答案by Naveen Ramawat

You have two options.
1 - Take sql date object and construct utils date using the getTime method of sql date
or
2 - call getTimeStamp instead of getDate , It will return object of sql timeStamp class that is actually child class of java.util.Date

你有两个选择。
1 - 使用 sql date 的 getTime 方法获取 sql date 对象并构造 utils date

2 - 调用 getTimeStamp 而不是 getDate ,它将返回 sql timeStamp 类的对象,该对象实际上是 java.util.Date 的子类

1 -  Date d1 = new Date(rs.getDate("date_time").getTime());
2 -  Date d2 = rs.getTimestamp("date_time");

回答by Sarjit Delivala

If combo box is not allowing object to inserted, while adding it to the combo_box use d_time.toString()method.

如果组合框不允许插入对象,则将其添加到 combo_box 使用d_time.toString()方法。