如何在Servlet中从数据库结果集中仅检索年份。

huangapple go评论62阅读模式
英文:

How to Retrieve Only Year in servlets while having resultset from the database

问题

我必须从数据库中检索Year(datepaid)。我应该使用哪个方法来获取Year(datepaid)

我尝试使用getDate("列名")方法,但出现错误,因为它在数据库中寻找日期格式,而我只检索了不在日期格式中的年份2020。

resultSet.getDate("列名")不起作用,我现在应该使用什么方法?

英文:

I have to retrieve the Year(datepaid) from the database. What method should I use to get Year(datepaid)

I have tried using the method getDate("column name"), it is showing error because it is looking for date format from the database but here I'm retrieving only Year 2020 which is not in the date format.

resultSet.getDate("column name") is not working, what method should I use now?

答案1

得分: 1

没有特殊方法来检索YEAR类型的列。您可以直接使用resultSet.getStringresultSet.getInt来获取该值。

英文:

There is no special method to retrive YEAR type column. You can just use resultSet.getString or resultSet.getInt to get the value.

答案2

得分: 0

确保在数据库中,您的列的类型为DATE/TIMESTAMP。并且getDate应该检索完整的日期。因此,在Java中,您可以使用以下代码来正确访问年份:

Calendar calendar = new GregorianCalendar();
calendar.setTime(date); //date = DB中的完整日期
int year = calendar.get(Calendar.YEAR);

如果在您的数据库中,日期列只包含年份(例如:2020、2019),可以是整数或字符串。因此,resultSet.getStringresultSet.getInt都可以使用。

英文:

Make sure that in the Database your column is of TYPE DATE/TIMESTAMP. And getDate should retrieve the complete date. So in java you can use the next code to properly access the year:

Calendar calendar = new GregorianCalendar();
calendar.setTime(date); //date = complete date from the DB
int year = calendar.get(Calendar.YEAR);

If in your DB the column of the date just have the year (Ex: 2020, 2019), could be an integer or a string. So resultSet.getString or resultSet.getInt would work.

huangapple
  • 本文由 发表于 2020年7月28日 04:34:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/63123138.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定