簡體   English   中英

為什么我無法從我的 Inner Join JDBC 查詢中獲得結果?

[英]Why can't I get results from my Inner Join JDBC Query?

這個 JDBC 查詢不返回任何東西,盡管它在我的 SQLite 數據庫瀏覽器上工作,無論我嘗試了什么。 該片段對我正在尋找的結果非常不言自明。

    public void getCountryIdLocationIdDepartmentIdParEmploye(Employe employe) {
        String query = "SELECT countries.country_id AS idc, locations.location_id AS idl, departments.department_id AS idd 
FROM countries 
INNER JOIN locations ON countries.country_id = locations.country_id 
INNER JOIN departments ON locations.location_id = departments.location_id 
INNER JOIN employees ON departments.department_id = employees.department_id 
AND employees.employee_id = ?";

        try {
            PreparedStatement ps = maConnexion.prepareStatement(query);
            ResultSet rs = ps.executeQuery();

            ps.setInt(1, employe.getId());
            setCountry_id(rs.getString("idc"));
            setLocation_id(rs.getInt("idl"));
            setDepartment_id(rs.getInt("idd"));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

我試圖替換setCountry_id(rs.getString("idc")); setCountry_id(rs.getString(1)); 等等,但不好,我的屬性保持不變。 問候,

PS:country_id確實是一個字符串

在兼容的 JDBC 驅動程序中,這應該拋出SQLException ,因為您在執行查詢設置了參數(這意味着應該不可能執行該語句)。 聽起來 SQLite JDBC 驅動程序在這方面存在錯誤。

執行需要設置參數:

try (PreparedStatement ps = maConnexion.prepareStatement(query)) {
    ps.setInt(1, employe.getId());

    try (ResultSet rs = ps.executeQuery()) {
        setCountry_id(rs.getString("idc"));
        setLocation_id(rs.getInt("idl"));
        setDepartment_id(rs.getInt("idd"));
    }
} catch (SQLException throwables) {
    throwables.printStackTrace();
}

還要觀察try-with-resources的使用,它確保您不會泄漏准備好的語句和結果集。

暫無
暫無

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

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