gpt4 book ai didi

java - com.microsoft.sqlserver.jdbc.SQLServerException : The value is not set for the parameter number 1

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:02:24 26 4
gpt4 key购买 nike

pstmt.setLong(1, id); 行有问题。我收到一个错误,指出参数编号 1 没有设置值。如果我使用不带问号的字符串 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;
}

最佳答案

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

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

关于java - com.microsoft.sqlserver.jdbc.SQLServerException : The value is not set for the parameter number 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47844731/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com