问题
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);}
回答1:
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);
}
回答2:
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();
}
回答3:
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
}
来源:https://stackoverflow.com/questions/25945249/java-scope-try-catch