我应该如何在mysql中将字符串转换为Year-MMMM格式,还是必须在控制器部分转换它?假设: 2019-02保存为2019-02,但我想要另一列将2019-02转换为2019-2月。
JSP部分
<form action="YearMonthController" method="post">
<input type="hidden" name="command" value="CREATE_YearMonth" />
Month with year: <input type="month" name="year_month">
<input type="submit">
</form>这是控制器部分
private void create_a_yearMonth_controller(HttpServletRequest request, HttpServletResponse response)
throws Exception {
String _yearMonth = request.getParameter("year_month");
YM ym = new YM(_yearMonth);
_ymDAO.create_a_yearMonth_dao(ym);
}这是DAO部分
public void create_a_yearMonth_dao(YM ym) throws Exception {
Connection connection = null;
PreparedStatement prepared_statement = null;
try {
connection = data_source.getConnection();
String sql = "INSERT INTO `years_months`\r\n" + "(yearMonth) \r\n" + "VALUES \r\n" + "(?);";
prepared_statement = connection.prepareStatement(sql);
prepared_statement.setString(1, ym.get_yearMonth());
prepared_statement.execute();
} finally {
close(connection, prepared_statement, null);
}
}这是一张桌子
CREATE TABLE `years_months` (
yearMonth VARCHAR(50) NOT NULL,
PRIMARY KEY (yearMonth)
);发布于 2019-02-10 16:37:23
因为MySQL没有year-month数据类型(至少我认为没有),所以我总是将year和month单独存储为2019-02 (因此varchar(50)列非常宽,char(7)也可以)。这是广泛认可的ISO 8601格式。
在Java语言中,我会使用YearMonth来表示年份和月份(不需要创建自己的类)。并根据演示需要对其进行格式化。YearMonth.toString生成上述ISO8601格式,然后YearMonth.parse将其解析回来,因此所有内容都能很好地结合在一起。
public void createAYearMonthDao(YearMonth ym) throws SQLException {
String sql = "INSERT INTO `years_months` (yearMonth) VALUES (?);";
try (Connection connection = data_source.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setString(1, ym.toString());
preparedStatement.execute();
}
}要在需要时生成像2019-February这样的字符串:
DateTimeFormatter ymFormatter = DateTimeFormatter.ofPattern("uuuu-MMMM", Locale.ENGLISH);
YearMonth ym = YearMonth.of(2019, Month.FEBRUARY);
String formattedYm = ym.format(ymFormatter);
System.out.println(formattedYm);输出:
2019-2月
YearMonth有分别获取年和月的方法,例如:
System.out.println("Year " + ym.getYear() + " month " + ym.getMonth());年2019月2月
注释中的另一个建议在MySQL中使用date,在Java中使用LocalDate也不错。优点:您可以在保存和检索时保存格式化和解析。缺点:您的数据库中有一个冗余的月日。
https://stackoverflow.com/questions/54614026
复制相似问题