com.microsoft.sqlserver.jdbc.SQLServerException:未为参数编号1设置值

时间:2017-12-16 10:35:46

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

我遇到了行PreparedStatement的问题。我收到一个错误,即没有为参数编号1设置该值。如果我使用没有问号的字符串SQL,它就可以工作。此外,当我使用ARM时,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; } 不会自动关闭,因此我必须关闭它们,最后似乎无法正常工作

{{1}}

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

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