【问题标题】:Retrieve and update field java检索和更新字段 java
【发布时间】:2020-10-29 16:14:02
【问题描述】:

使用 Java 我想从我的数据库中获取所有 ID,如果它等于 0,则选择 GW_STATUS。我使用以下 SQL 语句来实现这一点。

PreparedStatement get_id = con.prepareStatement("SELECT ID from SF_MESSAGES where GW_STATUS = 0");

获得 ID 后,我想根据 ID 将 GW_STATUS 更新为 1,如下面的代码所示,但执行代码时只更新一个字段。

PreparedStatement update = con.prepareStatement("update SF_MESSAGES set GW_STATUS=? where ID = ?");
    update.setInt(1,1);
    ResultSet x = get_id.executeQuery();
    while(x.next()){
        int uber = x.getInt(1);
        int array[] = new int[] {uber};
        for (int value : array) {
            System.out.println("Value = " + value); //Successfully obtains and prints each ID from the databse table
             update.setInt(2,value); // Only one ID is updated therefore only field updated
          }
    }
    int result = update.executeUpdate(); 
    System.out.println(result + " Records updated");

我尝试在 for 循环中使用另一个更新语句来更新获得的每个 ID,但这也不起作用。如何根据 ID 成功更新每个字段?

【问题讨论】:

  • 您在执行(或添加到批次)之前重复设置参数,这会覆盖您之前设置的任何值,因此只使用最后一个值。

标签: java sql jdbc prepared-statement


【解决方案1】:

您可以使整个处理过程变得非常简单。事实证明,您只想更新 GW_STATUS 等于 0 的 SF_MESSAGES,因此您的查询可能如下所示:

update SF_MESSAGES set GW_STATUS=1 where GW_STATUS=0

因此,您不必获取 ID,循环遍历它们,因此它是更有效的解决方案。

【讨论】:

  • 谢谢你的工作!我对试图过度设计解决方案感到内疚
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-05
  • 1970-01-01
  • 2016-12-17
  • 1970-01-01
  • 2014-01-23
  • 1970-01-01
  • 2012-02-21
相关资源
最近更新 更多