-1

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 :)

2 Answers2

0

You need to change your code like below

 try (Connection con = DriverManager.getConnection(infoHR.get("url"), infoHR.get("uname"), infoHR.get("pass")),
              Statement st = con.createStatement()) {
        //Error on line above relating to not initialising the object within the statement

        rs = st.executeQuery(query);

        rs.next();
        return rs.getString("first_name");
    }

Java 7 – allows us to declare resources to be used in a try block with the assurance that the resources will be closed when after the execution of that block.

you can find more here https://www.baeldung.com/java-try-with-resources

SSK
  • 3,444
  • 6
  • 32
  • 59
0

I think you mean to use:

    ResultSet rs;
    try (Connection con = DriverManager.getConnection(infoHR.get("url"), infoHR.get("uname"), infoHR.get("pass")); 
         Statement st = con.createStatement()) {
        //Error on line above relating to not initialising the object within the statement

        rs = st.executeQuery(query);

        rs.next();
        return rs.getString("first_name");
    }

Keep in mind that you are using try-with-resources block that closes the connection automatically. You don't need to declare the connection before and close it in the finnaly block.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
fjsv
  • 705
  • 10
  • 23