I have more than 2 classes that implemented the connection separately using try-catch, however when I tried to close the connection in the main it didn't work since it has a scope in the try-catch. My question is how do I close the connection while using the try-catch block?
Here is my code for one of my classes
String query="INSERT INTO branch (branch_Num , Street, Nieghbourhood,city) VALUES (?, ?,?, ?)";
try{
PreparedStatement ps;
String f="jdbc:derby://localhost:1527/coffeeZone";
connection = DriverManager.getConnection(f, "coffee", "1234");
ps=connection.prepareStatement(query);
ps.setString(1, bno);
ps.setString(2, strt);
ps.setString(3, nbh);
ps.setString(4, ci);
if (ps.executeUpdate()>0){
JOptionPane.showMessageDialog(null, "Complete! a new branch is added !");
}else
{
JOptionPane.showMessageDialog(null, "");
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null,ex);
}