将executeQuery转换为executeUpdate

时间:2017-10-09 01:04:59

标签: java sql sql-update

我正在尝试编写一个程序,允许用户更新sql数据库中列中的某个值。当我将数据写入数据库时​​,我正在使用executeQuery,我在复制和粘贴相同的代码时使用了更新值。

我更改了SQL语句以更新值,我读到我需要将executeQuery更改为executeUpdate。然而,当我去改变时,我收到一个错误,说int无法转换为ResultSet

case "G":

   System.out.println("Enter the player ID:");
   String playerId = FileUtility.getInput().nextLine();

   System.out.println("Here are the players");
   //theList = loadCampersFromDatabase(theList);
   for (Player camper : PlayerDAO.selectAllById(playerId)) {
       System.out.println(camper);
   }
   System.out.println("Enter the new amount paid");
   int newAmountPaid = FileUtility.getInput().nextInt();

   ArrayList<Player> players = new ArrayList();
   PreparedStatement ps = null;
   String sql = null;
   Connection conn = null;
   try {
      conn = ConnectionUtils.getConnection();

      sql = "UPDATE `Camper` SET `amountPaid`  where id like ?";

      ps = conn.prepareStatement(sql);
      ps.setString(1, playerId + "%");
      ResultSet rs = ps.executeUpdate();

      while (rs.next()) {

        int newId = rs.getInt("id");
        String firstName = rs.getString("firstName");
        String lastName = rs.getString("lastName");
        String parentsName = rs.getString("parentsName");
        int phoneNumber = rs.getInt("phoneNumber");
        String email = rs.getString("email");
        int amountPaid = rs.getInt("amountPaid");
        players.add(new Player(newId, firstName, lastName, 
        parentsName, phoneNumber, email, amountPaid));

      }

   } catch (Exception e) {
      String errorMessage = e.getMessage();
      e.printStackTrace();
   } finally {
      DbUtils.close(ps, conn);
   }

   break;

2 个答案:

答案 0 :(得分:0)

您对executeUpdate()和executeQuery()方法感到困惑。

  1. 的executeUpdate(): 执行&#39;更新&#39;和其他语句,它返回一个int值,它告诉你更新的语句会影响多少行。
  2. 的executeQuery() - 这种方法只执行“SELECT&#39;查询并返回ResultSet实例,可以进一步在循环内部进行交互(while),通常使用select语句获取并显示所有记录。
  3. 我建议你重做你方法的逻辑。 我可以看到您的更新查询,您只传递了一个值为&#39; id&#39;在查询中,而不是在&#39; amountPaid&#39; 重写update语句并使用executeUpdate()方法进行更新。

答案 1 :(得分:0)

只需将Resultset及其相应的while循环移除为操作查询(UPDATEINSERTDELETECREATE,{{ 1}},ALTER)不返回结果集,仅返回DROP个查询。下面假设您打算将 newAmountPaid 绑定到查询中:

SELECT