I still have problems closing my connections correctly, the error I have now is that the Connection, Statement and ResultSet variables say that I must create them locally, so what should I do?
My code:
String showTableSQL = "SELECT * FROM llamadas";
try {
Connection conn = conexion.getConnection();
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(showTableSQL);
while (rs.next()) {
// Obtenemos el modelo del JTable
model = (DefaultTableModel) table.getModel();
// Agregamos las filas al JTable
model.addRow(new Object[]{
Integer.toString(rs.getInt(1)),
rs.getString(2),
rs.getString(3),
rs.getString(4),
rs.getString(5),
Integer.toString(rs.getInt(6)),
Double.toString(rs.getDouble(7))
});
}
} catch (SQLException errorSQL) { errorSQL.printStackTrace(); }
finally { // Cerramos las conexiones, en orden inverso a su apertura
try { rs.close(); } catch (Exception errorRS) { errorRS.printStackTrace(); }
try { st.close(); } catch (Exception errorST) { errorST.printStackTrace(); }
try { conn.close(); } catch (Exception errorCONN) { errorCONN.printStackTrace(); }
}
the mistake is in
rs, st and conn: cannot be resolved, create local variable
I hope you can help me solve this, I've been trying for 2 days. I am learning MySQL still.
Any help is appreciated.
Properly closing instances of
Connection
,Statement
,ResultSet
and properly handling all errors that may result using the typical pattern oftry-catch-finally
is not easy. And if you do, the code isn't elegant.For example, even if you fix your immediate problem by moving the variable definitions out of the
try
, the code still has at least one design flaw.Let's say that you correct the code in this way (and by the way, reading the comments under @Dev Joel's answer, it should be clarified that it is necessary to initialize the variables to some value like
null
. Without that, the Java compiler cannot guarantee that the variables have some value assigned when they are used in the blockfinally
, and that is why it complains. And in fact, this point is linked to the defect that I am going to demonstrate) :Now imagine that some error occurs in this statement:
That causes
st
andrs
to be left with valuesnull
, and now, when the blockfinally
executes, as muchrs.close();
asst.close()
they are going to throw aNullPointerException
that could have been avoided.So the correct way to handle the block
finally
is to check if the variables are anull
before trying to close them:A better alternative
The above simply illustrates that it is easy to make mistakes with this type of code due to its complexity. And even if you get it right, the complexity obscures the true purpose of the code.
For this reason, as of Java 7, there is a better way to handle this type of situation, using
try-with-resources
. Using this technique, notice how your code can be simplified and how clear it becomes:If you read the documentation , you will see that this simplified code structure automatically handles the following aspects:
.close()
are executed automatically at the end of the blocktry
and in the reverse order of the opening of the different instances..close()
, those exceptions do not override the main exception, if any.try
or with the.close()
, ite.printStackTrace()
includes the information of all the errors automatically.rs
st
The error is that you are declaring the and variablesconn
inside the first blocktry{}catch(){}
and when you try to access in thetry{}catch(){}
delfinally
they are no longer accessible as they are out of scope.The scope of your three variables in your program is the first
try{} catch(){}
. To fix this, declare the variables at the method level (beforetry{}catch(){}
)One way would be to enclose everything in a try and catch more or less like this
Singleton connection
Example