1. 程式人生 > >【數據庫】java鏈接jdbc 釋放資源

【數據庫】java鏈接jdbc 釋放資源

nic 釋放資源 select 快速 () 步驟 http tin class


/*
* 編寫快速 入門的jdbc 程序 :
*
* 1. 先導入 具體的驅動jar包
* 2. 編寫一個類 , 寫jdbc 的程序
*
* 具體的編寫 java類的 代碼的步驟:
*
* 第一步: 註冊驅動 --- 告訴 具體的要操作的是那個 數據庫
* 第二步: 建立與 數據庫的鏈接---Connection
* 第三步: 獲得可以發送 sql 語句的 statement 對象
* 第四步: 執行sql 語句, 拿到 結果集對象
* 第五步: 解析結果集中的數據
* 第六步: 釋放資源
*
*/

@Test
public void test2() {


Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 第一步: 註冊驅動
// DriverManager.registerDriver(new Driver());

//這裏 本來是 加載字節碼, 但是 加載字節碼的 時候 又 會執行 這個Driver類的靜態代碼快, 而靜態代碼塊 有完成了驅動的註冊, 所以
// 這行代碼 就是那麽巧 ...
Class.forName("com.mysql.jdbc.Driver");

// 第二步: 建立與 數據庫的鏈接
// http://localhost:8080/day15/1.html

//通常 可以簡寫 為 :  jdbc:mysql:///day15_jdbc
conn = DriverManager.getConnection("jdbc:mysql:///day15_jdbc", "root", "abc");



// 第三步:獲得可以發送 sql 語句的 statement 對象

stmt = conn.createStatement();

// 第四步: 執行sql 語句, 拿到 結果集對象
// rs , 就封裝了這個查詢的結果
rs = stmt.executeQuery("select * from users");

// 第五步: 解析結果集中的數據
while(rs.next()){

int id = rs.getInt("id");
String username = rs.getString("username");
String password = rs.getString("password");
String nickname = rs.getString("nickname");

System.out.println("id: " + id+",username : " + username+", password : " + password +", nickname : " + nickname);
}


} catch (Exception e) {
e.printStackTrace();
}finally{
// 第六步: 釋放資源 --- 由於 數據庫 鏈接非常的稀缺, 所以 在 操作完成後,記得釋放資源 , 都會放到 finally 代碼塊 中

if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs =null;
}

if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt=null;
}

if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn=null;
}

}
}

【數據庫】java鏈接jdbc 釋放資源