Java com.microsoft.sqlserver.jdbc.SQLServerException:未为参数1设置该值

Java com.microsoft.sqlserver.jdbc.SQLServerException:未为参数1设置该值,java,sql-server,jdbc,prepared-statement,resultset,Java,Sql Server,Jdbc,Prepared Statement,Resultset,我对linepstmt.setLong(1,id)有问题。我得到一个错误,没有为参数1设置值。如果我使用不带问号的字符串SQL,它就可以工作。另外,当我使用ARM时,PreparedStatement和ResultSet不会自动关闭,因此我必须关闭它们,最后似乎也不起作用 @Override public Company getCompany(long id) { Connection con = ConnectionPool.getInstance().getConnectio

我对line
pstmt.setLong(1,id)有问题。我得到一个错误,没有为参数1设置值。如果我使用不带问号的字符串SQL,它就可以工作。另外,当我使用ARM时,
PreparedStatement
ResultSet
不会自动关闭,因此我必须关闭它们,最后似乎也不起作用

@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;  
}

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

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

您需要在执行
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);  
}