【发布时间】:2019-07-03 23:19:00
【问题描述】:
我应该如何在 mysql 中将字符串转换为 Year-MMMM 格式,还是必须在控制器部分进行转换? 假设:2019-02 被保存为 2019-02,但我想要另一列将 2019-02 转换为 2019-February。
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)
);
【问题讨论】:
-
我建议您将年月存储为日期,也许将天始终设置为 1,然后您可以使用标准格式函数在 sql 或 java 中格式化日期。此外,在要与日期进行比较的查询中使用该列会容易得多。
-
如果我使用日期,我会收到以下错误。 HTTP 状态 500 - com.mysql.jdbc.MysqlDataTruncation:数据截断:不正确的日期值:第 1 行的列“yearMonth”的“2019-02”
-
当然你需要给一天,就像我在之前的评论中提到的那样,只需将它设置为 1
-
您能详细说明一下吗?会很有帮助。
-
不确定您的意思,只需在存储之前将'-01'添加到字符串中。 Mysql应该能够自动将格式为'yyyy-mm-dd'的字符串转换为日期