[英]Why can't I get results from my Inner Join JDBC Query?
This JDBC query does not return anything despite it working on my SQLite Database Browser, no matter what I tried.这个 JDBC 查询不返回任何东西,尽管它在我的 SQLite 数据库浏览器上工作,无论我尝试了什么。 The snippet is pretty self-explanatory of the results I'm looking for.
该片段对我正在寻找的结果非常不言自明。
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();
}
}
I've tried to replace setCountry_id(rs.getString("idc"));
我试图替换
setCountry_id(rs.getString("idc"));
with setCountry_id(rs.getString(1));
与
setCountry_id(rs.getString(1));
etc. already but no good, my attributes stay unchanged.等等,但不好,我的属性保持不变。 Regards,
问候,
PS: country_id is indeed a string PS:country_id确实是一个字符串
In a compliant JDBC driver this should throw a SQLException
because you set the parameter after executing the query (which means it should not be possible to execute the statement).在兼容的 JDBC 驱动程序中,这应该抛出
SQLException
,因为您在执行查询后设置了参数(这意味着应该不可能执行该语句)。 It sounds like the SQLite JDBC driver has a bug in that regard.听起来 SQLite JDBC 驱动程序在这方面存在错误。
You need to set the parameter before executing:执行前需要设置参数:
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();
}
Also observe the use of try-with-resources , which ensures you don't leak the prepared statement and result set.还要观察try-with-resources的使用,它确保您不会泄漏准备好的语句和结果集。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.