简体   繁体   中英

Java Scope Try/Catch

Fairly new to Java and am trying to better understand a few things. I understand that try/catch statement variables only have scope within that statement. I am trying to learn java db sql and am running into an issue.

final String DB_URL = "jdbc:derby://localhost:1527/Customers";    
Connection conn = DriverManager.getConnection(DB_URL);

This creates the connection with my database. I need to have this in a try/catch statement. I want to access the conn variable again at the end of the program to close the connection. I tried to declare this variable at the top of my program but it won't let me as it needs a try/catch. What is the best way to tackle this?

As suggested below I created it as a variable. I am trying to close the connection with my exit button but the code is not getting executed. With the if statement the program doesn't close nor does the System.out.print message fires. The connection is starting OK but not closing.

if (conn != null){
   conn.close();
   System.out.println("Connection Closed");
   System.exit(0);}

You could do it by declaring Connection object outside the try/catch block, and creating it within the try{}

final String DB_URL = "jdbc:derby://localhost:1527/Customers";    
Connection conn = null;
try {
     conn = DriverManager.getConnection(DB_URL);
} catch(Exception e) {
  System.out.println("Exception "+e);
}

The solution is to separate the variable declaration from its instantiation. At the top of your class, put the declaration:

Connection conn = null;

Then you can put the instantiation in a try/catch block.

try {
    conn = DriverManager.getConnection(DB_URL);
}
catch (SQLException exception) {
    // Handle error.
}

Finally, when you clean up, add a null check.

if (conn != null) {
    conn.close();
}

You should declare connection variable outside the try block

Connection conn = null;
try {
conn = Connection conn = DriverManager.getConnection(url)
} catch (SQLException e) {//log exception} 


and at the end of your program you can close it like this

 if (conn != null) {
     try{conn.close();} 
     catch(Exception e) {//log exception}
  }

Starting from Java 7 you can use try with resource and it will automatically release the resource , but the variable conn is only accessible inside the try block.

try (Connection conn = DriverManager.getConnection(url)) {
            System.out.println("Connecting...");

            System.out.println("Connected");


        } catch (SQLException e) {
            //log exception
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM