'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;
}
//Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.List.iterator()" because "lo" is null
Solution 1:[1]
You should use ResultSet
to read your Order
of SQL query, and add the Order
into your List, like below:
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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Kai-Sheng Yang |