So I am using JDBC to connect to a local host MySQL server, and when I am coding my try block to connect with the server and send a query I am getting a 'Cannot find symbol'
error.
I understand that this is because the object is initialised inside the try condition and I am trying to use it from a finally condition, but I cannot initialise it outside of the try block either, as I get an error saying 'The try-with-resources resource must be a variable declaration or an expression denoting to a final or effectively final variable'
The general idea I am trying to code up is being able to close the connection to the database in the finally block regardless of whether an exception is thrown or not. The code in question is as follows (Lines with errors highlighted) :
public static String returnEmployeeName(String ID) throws ClassNotFoundException, SQLException {
HashMap<String, String> infoHR = connectionInfoHR();
String query = "SELECT first_name FROM employees WHERE employee_id = '" + ID + "'";
Class.forName("com.mysql.cj.jdbc.Driver");
Statement st;
ResultSet rs;
Connection con;
try (con = DriverManager.getConnection(infoHR.get("url"), infoHR.get("uname"), infoHR.get("pass"))) {
//Error on line above relating to not initialising the object within the statement
st = con.createStatement();
rs = st.executeQuery(query);
rs.next();
return rs.getString("first_name");
} finally {
st.close();
con.close();
}
}
Cheers in advance for any help that can be provided :)