如何从Java设置当前日期到MySQL日期列?

时间:2010-03-07 08:04:48

标签: java mysql

我在表中有一个DATE数据类型mysql列。我想从我的java代码中设置该列的值,格式为YYYY-MM-DD

我使用以下代码来测试这些格式..

Calendar c = Calendar.getInstance();
c.setTime(new Date());
String d = c.YEAR+ "-"+c.MONTH+"-"+c.DATE;

但如果我在控制台中打印出该值,我会得到一些奇怪的输出。请帮忙。我怎么能做到这一点?

2 个答案:

答案 0 :(得分:3)

在JDBC中,您可以使用setDate()方法在预准备语句中设置DATE值,请参阅the API of PreparedStatement。这会将值转换为数据库中的DATE类型。

PreparedStatement prep = con.prepareStatement("some query with a DATE field");
Date d = new Date(System.currentTimeMillis());
// just an example (its the java.sql.Date class, not java.util.Date)
prep.setDate(index, d);
// ...

要使用DATE字段的值返回此 java.sql.Date 对象,请使用ResultSet classgetDate()方法。

ResultSet res = con.executeQuery("some query with a DATE field");
Date d = res.getDate(index);

您可以使用d对象,例如java.util.Date对象(如在Calendar对象中使用),因为它从中延伸。

答案 1 :(得分:2)

你要做的是:

String d = c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH) + "-" + c.get(Calendar.DATE)

如果我没记错的话,你还必须在月份中添加+1,因为它返回偏移量(从0开始计算)而不是仅仅是月值(这对我来说是愚蠢的,但我没有做设计)。

此外,您可能希望检查SimpleDateFormat及其功能,以便很好地格式化日期。

相关问题