David Thomlinson David Thomlinson - 5 months ago 7
SQL Question

Initialize variable error Java

I am attempting to print some results from an SQL statement inside of Java and I am receiving an error saying these variables need to be initialized but I'm not sure how to go about doing this other than setting them to null which isn't what I want to do here, my error is when attempting to close

st
,
rs
and
con
, I am prompted to initialize the variables but this just sets them to
null
, here is my code so far:

public static void copyFolder(File src, File dest)
throws IOException {
Connection con;
Statement st;
ResultSet rs;

try {
con = DriverManager.getConnection("removed as it houses sensitive data");
st = con.createStatement();
String s = "SELECT Code FROM dbo.\"FK Facades$Dimension Value\" WHERE [Dimension Code] = 'PROJECT'";
rs = st.executeQuery(s);
while (rs.next()) {
rs.getString(1);
System.out.print(rs);
}
} catch (Exception e) {
System.out.println("No connectarino");
} finally {
try {
st.close();
rs.close();
con.close();
} catch (Exception e) {
System.out.println("No");
}
}
}

Answer

In addition to what is already said, you should start using try-with-resources like this:

    try (Connection con = DriverManager.getConnection("removed as it houses sensitive data");
         Statement st = con.createStatement();
         ResultSet rs = st.executeQuery("...")) {
        // your code here
    }

This automatically closes the instances for you, and even gets the corner cases (i.e. exception in close()) right.

Comments