【发布时间】: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