提问人:Hoàng Việt 提问时间:4/20/2022 更新时间:5/7/2022 访问量:96
结果集要列出 null [duplicate]
Resultset To List null [duplicate]
问:
public List<Order> getAllOrdersByCustomerId(int customerId) throws SQLException {
List<Order> AllOrdersByCustomerId = new ArrayList<>();
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
String sqlQuery = "SELECT * FROM dbo.Orders WHERE customer_id = ?";
con = JDBCConnection.getConnection();
pstmt = con.prepareStatement(sqlQuery);
pstmt.setInt(1, customerId);
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
JDBCConnection.closeConnection(con);
}
if (rs != null) {
JDBCConnection.closeResultSet(rs);
}
}
return AllOrdersByCustomerId;
}
线程“main”java.lang.NullPointerException 中的异常:无法调用“java.util.List.iterator()”,因为“lo”为 null
答:
0赞
Kai-Sheng Yang
4/20/2022
#1
你应该用来读取你的 SQL 查询,并将 添加到你的列表中,如下所示:ResultSet
Order
Order
public List<Order> getAllOrdersByCustomerId(int customerId) throws SQLException {
List<Order> allOrdersByCustomerId = new ArrayList<>();
String sqlQuery = "SELECT * FROM dbo.Orders WHERE customer_id = ?";
try (Connection con = JDBCConnection.getConnection();
PreparedStatement pstmt = con.prepareStatement(sqlQuery)) {
pstmt.setInt(1, customerId);
try (ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
Order order = new Order();
String id = rs.getString("ORDER_ID");
order.setId(id);
// get and set your values ...
allOrdersByCustomerId.add(order);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return allOrdersByCustomerId;
}
评论
executeUpdate()
lo