【问题标题】:com.microsoft.sqlserver.jdbc.SQLServerException: The value is not set for the parameter number 1com.microsoft.sqlserver.jdbc.SQLServerException: 未为参数号 1 设置值
【发布时间】:2026-01-04 07:40:01
【问题描述】:

pstmt.setLong(1, id); 行有问题。我收到一个错误,即没有为参数号 1 设置值。如果我使用不带问号的 String SQL,它可以工作。另外,当我使用 ARM 时,PreparedStatementResultSet 不会自动关闭,所以我必须关闭它们,最后似乎也不起作用

@Override  
public Company getCompany(long id) {  
    Connection con = ConnectionPool.getInstance().getConnection();  
    String sql = "SELECT * FROM Company WHERE ID=?";  
    //String sql = "SELECT * FROM Company WHERE ID=" + id;  
    Company company = new Company();  
    try (  
        PreparedStatement pstmt = con.prepareStatement(sql);  
        ResultSet rs = pstmt.executeQuery();)  
        {  
        pstmt.setLong(1, id);  
        if (rs.next()) { 
            company.setId(rs.getLong(1));  
            company.setCompName(rs.getString(2)); 
            company.setPassword(rs.getString(3));  
            company.setEmail(rs.getString(4)); 
        } else {  
            System.out.println("Company with ID: " + id + " could not be found\n"); 
        }  
        pstmt.close();  
        rs.close();  
    } catch (SQLException e) {  
        CouponSystemException ex = new CouponSystemException("Company with ID: " + id + " could not be retrieved\n", e);  
        System.out.println(ex.getMessage());  
        System.out.println(e);  
    }  
    ConnectionPool.getInstance().returnConnection(con);  
    return company;  
}

【问题讨论】:

    标签: java sql-server jdbc prepared-statement resultset


    【解决方案1】:

    在执行查询之前设置参数。 此外,您无需关闭在 try-with-resource 语句中定义的语句和结果集,因为它们会在您离开 try 范围时自动关闭。

    try(PreparedStatement pstmt = con.prepareStatement(sql)) {
        pstmt.setLong(1, id);
        try(ResultSet rs = pstmt.executeQuery()) {
            // do stuff
        }
    }
    

    【讨论】:

      【解决方案2】:

      您需要设置PreparedStatement 的参数在执行之前。另请注意,您使用的是 try-with-resource 语法,您不应该自己关闭资源:

      try (PreparedStatement pstmt = con.prepareStatement(sql)) {
          pstmt.setLong(1, id);
          try (ResultSet rs = pstmt.executeQuery()) {
              if (rs.next()) { 
                  company.setId(rs.getLong(1));  
                  company.setCompName(rs.getString(2)); 
                  company.setPassword(rs.getString(3));  
                  company.setEmail(rs.getString(4)); 
              } else {  
                  System.out.println("Company with ID: " + id + " could not be found\n"); 
              }  
          }
      } catch (SQLException e) {  
          CouponSystemException ex = new CouponSystemException("Company with ID: " + id + " could not be retrieved\n", e);  
          System.out.println(ex.getMessage());  
          System.out.println(e);  
      }  
      

      【讨论】: