在上篇博客介紹了jdbc的基本用法,其中有一段代碼是這樣的:
public static void main(String[] args) {
Connection conn = null;
Statement state = null;
ResultSet set = null;
try {
//註冊數據庫驅動
DriverManager.registerDriver(new Driver());
//獲取數據庫連接
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "");
//獲取傳輸器對象
state= conn.createStatement();
//利用傳輸器對象執行sql語句
set=state.executeQuery("select * from emp");
while(set.next()){
System.out.println(set.getString("name"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
set.close();
state.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
可以看到這些代碼的最後有三句XX.close釋放資源,但是這樣寫釋放資源還是有問題的,由於上篇博客是入門的,所以就不探討過於複雜的問題,把重點放在如何使用jdbc上了。
那麼本篇博客將討論如何釋放資源。
在jdbc中Connection是非常稀有的資源,使用完之後應當馬上釋放,甚至還要以”遲佔用,早釋放“的原則使用,也就是說在使用的過程中儘可能地要用的時候才創建Connection一用完應當立刻關閉釋放。
而且上面那段代碼一開始:
Connection conn = null;
Statement state = null;
ResultSet set = null;
就定義了三個空值,如果往下執行,還沒執行到給他們三個變量賦值就拋異常了,這個時候程序會catch一場然後執行finally裏面的語句,但是這個時候set,state,conn都是空的,空的對象調用方法又會拋出nullpointexception,這個時候整個程序就崩潰了。所以在關閉之前必須先判空 。
儘管進行了判空再關閉資源還是會有問題的,請看最後關閉資源的時候:
try {
set.close();
state.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
把所有關閉語句寫在同一個try塊裏面,一旦前面的管比喻句拋異常,後面的關閉語句就無法執行了,所以不能這樣寫,要給每個關閉語句一個try塊。最後爲了保證資源能夠釋放,還有在每個關閉語句的後面加一個finally,在finally裏給要關閉的資源賦值爲空。這樣就算在關閉過程中拋異常不能及時關閉,但是由於賦值爲空,沒有引用該資源,在垃圾回收的時候也能夠回收。
下面是嚴謹正確的關閉資源的寫法,對於其它關閉資源也可以參考這種寫法:
package com.javy.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mysql.jdbc.Driver;
public class JdbcDemo1 {
public static void main(String[] args) {
Connection conn = null;
Statement state = null;
ResultSet set = null;
try {
// 註冊數據庫驅動
DriverManager.registerDriver(new Driver());
Class.forName("com.mysql.jdbc.Driver");
// 獲取數據庫連接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "");
// 獲取傳輸器對象
state = conn.createStatement();
// 利用傳輸器對象執行sql語句
set = state.executeQuery("select * from emp");
while (set.next()) {
System.out.println(set.getString("name"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
conn = null;
}
try {
set.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
set = null;
}
try {
state.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
state = null;
}
}
}
}