编辑建议的答案是不可接受的,不能为我想象的每种方法声明其他方法吗?必须有资源解决方案的嵌套尝试。
如何将try语句与带参数的prepare语句一起使用?
我遇到以下两行错误。
preparedStatement.setString(1, uuid);
preparedStatement.setString(2, emailAddress);
错误声明最终或有效的最终变量已被删除
public UserBean getUserDevices(final String emailAddress, final String uuid) throws SQLException {
UserBean userBean = null;
String query = "SELECT user.id, user.emailAddress, device.uuid, device.active, device.user_id FROM user " +
"LEFT JOIN device ON user.id = device.user_id AND device.uuid = ? " +
"WHERE user.emailAddress = ?";
try (Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, uuid);
preparedStatement.setString(2, emailAddress);
ResultSet resultSet = preparedStatement.executeQuery();
) {
while(resultSet.next()) {
if(userBean == null) { // initialize user once while iterating for devices
userBean = new UserBean(resultSet.getInt("user.id"), resultSet.getString("user.emailAddress"), null);
}
if(resultSet.getString("device.uuid") != null) { // if device exists (it's a LEFT JOIN) then add
userBean.getDevices().add(new DeviceBean(0, resultSet.getString("device.uuid"), resultSet.getBoolean("device.active"), resultSet.getInt("device.user_id")));
}
}
}
return userBean;
}
答案 0 :(得分:3)
使用内部尝试使用资源,在使用资源进行外部尝试之后,初始化该语句,然后对resultSet使用内部尝试和资源。
public UserBean getUserDevices(final String emailAddress, final String uuid) throws SQLException {
UserBean userBean = null;
String query = "SELECT user.id, user.emailAddress, device.uuid, device.active, device.user_id FROM user " +
"LEFT JOIN device ON user.id = device.user_id AND device.uuid = ? " +
"WHERE user.emailAddress = ?";
try (Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(query);
) {
preparedStatement.setString(1, uuid);
preparedStatement.setString(2, emailAddress);
try(ResultSet resultSet = preparedStatement.executeQuery();) {
while(resultSet.next()) {
if(userBean == null) { // initialize user once while iterating for devices
userBean = new UserBean(resultSet.getInt("user.id"), resultSet.getString("user.emailAddress"), null);
}
if(resultSet.getString("device.uuid") != null) { // if device exists (it's a LEFT JOIN) then add
userBean.getDevices().add(new DeviceBean(0, resultSet.getString("device.uuid"), resultSet.getBoolean("device.active"), resultSet.getInt("device.user_id")));
}
}
}
}
return userBean;
}