繁体   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