【发布时间】:2026-01-04 07:40:01
【问题描述】:
pstmt.setLong(1, id); 行有问题。我收到一个错误,即没有为参数号 1 设置值。如果我使用不带问号的 String 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;
}
【问题讨论】:
标签: java sql-server jdbc prepared-statement resultset