结果集要列出 null [duplicate]

Resultset To List null [duplicate]

提问人:Hoàng Việt 提问时间:4/20/2022 更新时间:5/7/2022 访问量:96

问:

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

java 列表 arraylist nullpointerException 结果集

评论

0赞 Jim Garrison 4/20/2022
为什么要查询?在哪里定义?完全不清楚你要完成什么。executeUpdate()lo
0赞 Community 4/20/2022
请澄清您的具体问题或提供其他详细信息以准确说明您的需求。正如目前所写的那样,很难确切地说出你在问什么。

答:

0赞 Kai-Sheng Yang 4/20/2022 #1

你应该用来读取你的 SQL 查询,并将 添加到你的列表中,如下所示:ResultSetOrderOrder

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;
}