簡體   English   中英

預處理語句僅檢索第一行

[英]Prepared Statement only retrieves the first row

我正在開發一個Web應用程序,用戶可以在其中插入許多“產品”。 這些產品將插入MySQL數據庫中。 嘗試從數據庫表中檢索數據時出現問題。 這是我的方法:

public ArrayList<Product> getProductByAppId(int appId) {
        ArrayList<Product> list = new ArrayList<Product>();
        String query = "select prodId from app_prod where appId = ?";

        try {
            preparedStatement = connection.prepareStatement(query);
            preparedStatement.setInt(1, appId);
            resultSet = preparedStatement.executeQuery();

            while (resultSet.next()) {
                Product item = getProductById(resultSet.getInt("prodId"));
                list.add(item);
            } 
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
}

此方法只是獲取一個int作為參數,並從表app_prod檢索我已存儲的所有對象。 方法getProductById是輔助方法,可以正常工作。 當我嘗試調試代碼時,我看到進入while周期僅一次! 因此,我所看到的只是數據庫中的第一個元素,但是數據庫中我不止一個產品。

為了簡化起見,我省略了打開和關閉連接的方法,因為它們可以正常工作。

我認為該錯誤非常明顯,但我看不到它。

好的,問題如下:

resultSet被聲明為全局變量,兩種方法都在使用它。
當第二種方法更改其內容並通過以下方法進行訪問時:

resultSet.next();

並到達結尾:

主要的外部循環嘗試執行resultSet.next() ,因為它已經預先在getProductById方法中到達其末尾,所以它直接從循環中退出。

    List<Product> list = new ArrayList<>();
    try (PreparedStatement preparedStatement = connection.prepareStatement(query)) {
        preparedStatement.setInt(1, appId);
        try (resultSet = preparedStatement.executeQuery()) {
            while (resultSet.next()) {
                Product item = getProductById(resultSet.getInt("prodId"));
                list.add(item);
            } 
            return list;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

try-with-resources確保語句和結果集關閉(即使返回也是如此)。

現在變量也是局部的。 可能是問題:也許你重用這些全球領域getProductById resultSet是我的猜測。 (對不起。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM