【问题标题】:Is it possible to call DATE_ADD() in Java and store the value in a temporary date variable?是否可以在 Java 中调用 DATE_ADD() 并将值存储在临时日期变量中?
【发布时间】:2013-01-07 23:54:51
【问题描述】:

我对在 MySQL 数据库中为 Date 添加天数有疑问。 以下是我的代码:

res=stat.executeQuery("select st_date from tmp1 where st_date = '"+t1.getText()+"'");
while(res.next())
{
    System.out.println(res.getDate(1));
    int i=0;
    while(i<14)
    {
        statement.executeUpdate("Insert into datetab values(DATE_ADD('"
            +res.getDate("st_date")+"',INTERVAL 1 DAY),'"+tempname+"')");
        i=i+1;
    }
}

datetab 表中的所有更新都发生了,但是有一个问题。我将用一个例子来解释这个问题。如果 tmp1 表中的日期是 28-12-2000,那么在使用 date_add() 执行插入查询后,会发生 13 次新插入,但所有这些插入都是“29-12-2000”。

【问题讨论】:

  • 我实际上并不了解您的目标是什么,但据我所知,在 SQL 中,如果您将“28-12-2000”日期值作为 X,并且您想插入下一个一天只是:X + 1

标签: java mysql date


【解决方案1】:

如果 tmp1 表中的日期是 28-12-2000 那么在使用 date_add() 执行插入查询后,会发生 13 个新插入,但所有这些插入都是“29-12-2000”。

因为这正是您所要求的。您的插入语句是:

"Insert into datetab values(DATE_ADD('" + res.getDate("st_date") + 
    "',INTERVAL 1 DAY),'" + tempname + "')"

由于read.getDate 在循环中没有变化,所以每次交互都会插入相同的值。

而不是"Interval 1 DAY",使用"Interval " + i + " Day" 应该插入不同的日期。这就是你要找的吗?

【讨论】:

  • 谢谢大哥...我在想象,我做了,但忘记放+号,显示错误类型不兼容。谢谢。你为我节省了一个小时。
  • 没用。没有错误,但没有更新任何内容。
  • 这不太可能,这可能是您的代码中的其他错误吗?我建议您逐步执行程序,将参数分配给executeUpdateString 并在调用executeUpdate 之前打印它并尝试在交互式sql 会话中执行它
猜你喜欢
  • 1970-01-01
  • 2018-11-04
  • 1970-01-01
  • 1970-01-01
  • 2012-04-04
  • 1970-01-01
  • 2021-11-29
  • 2020-11-06
  • 1970-01-01
相关资源
最近更新 更多