I'm getting a lot of errors in Eclipse with the misuse of the localization of the PreparedStatement
and ResulSet
. I have been guided by the Oracle documentation but Eclipse keeps giving me problems.
My code:
public List<String> obtenerDato_UsuarioExistente(String id_usuario) {
sSQL = "SELECT FROM usuarios WHERE id_usuario=?";
List<String> dato_UsuarioExistente = new ArrayList<String>();
// Java 7 try-with-resources
try (PreparedStatement pstm = con.prepareStatement(sSQL);
ResultSet rs = pstm.executeQuery()) {
pstm.setInt(1, Integer.parseInt(id_usuario));
rs = pstm.executeQuery();
rs.first();
dato_UsuarioExistente.add(Integer.toString(rs.getInt(1))); // id_usuario
dato_UsuarioExistente.add(rs.getString(2)); // nombre
dato_UsuarioExistente.add(rs.getString(3)); // apellido
dato_UsuarioExistente.add(rs.getString(4)); // usuario
dato_UsuarioExistente.add(rs.getString(5)); // contrasena
dato_UsuarioExistente.add(rs.getString(6)); // perfil
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "SQLException:\n" + e, "Error", JOptionPane.ERROR_MESSAGE);
}
return dato_UsuarioExistente;
}
Error I get on the line rs = pstm.executeQuery();
:
The resource rs of a try-with-resources statement cannot be assigned
As I have seen, there are many ways to do it, on this website they indicate the following:
try (Connection connection = getConnection();
Prepared pStatement = connection.prepareStatement(sql);
ResultSet resultSet = pStatement.executeQuery()) {
while (resultSet.next()) {
// gestionar resultset
}
} catch (SQLException e) {
throw newException;
}
On the Oracle website they indicate the following:
try (Statement stmt = con.createStatement()) {
ResultSet rs = stmt.executeQuery(query);
// ........................
}
} catch (SQLException e) {
JDBCTutorialUtilities.printSQLException(e);
}
and many others, sending the SQL statement in different places.
I'm very confused, any help would be appreciated as I'm learning and I don't really know what is correct.
There are 2 little problems with the code you have now:
You're executing
pstm.executeQuery()
2 times, and the second time is invalid because you can't reassign to a variable (rs
) that was initialized intry-with-resources
it (that's what the error is telling you).In this case, you cannot put the initialization of
PreparedStatement
the and theResultSet
within the same blocktry
, because you need to assign a parameter to the prepared statement before you can execute the query.To remedy this, you can simply split it into 2 blocks: