JDBC釋放資源
阿新 • • 發佈:2018-11-27
JDBCTest:
package com.test.example; 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; import com.test.util.JDBCUtil; public class JDBCTest { public static void main(String[] args) { // TODO Auto-generated method stub Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { //1. 註冊驅動 DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //2. 建立連線 引數一: 協議 + 訪問的資料庫 , 引數二: 使用者名稱 , 引數三: 密碼。 connection = DriverManager.getConnection("jdbc:mysql://localhost/jdbc", "root", "root"); //3. 建立statement , 跟資料庫打交道,一定需要這個物件 statement = connection.createStatement(); //4. 執行查詢 , 得到結果集 String sql = "select * from stu"; resultSet = statement.executeQuery(sql); //5. 遍歷查詢每一條記錄 while(resultSet.next()){ int id = resultSet.getInt("id"); String name = resultSet.getString("name"); int age = resultSet.getInt("age"); System.out.println("id="+id+",name="+name+",age="+age); } // resultSet.close(); // Statement.close(); // connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ JDBCUtil.close(connection, resultSet, statement); } } }
JDBCUtil:
package com.test.util; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBCUtil { public static void close(Connection connection,ResultSet resultSet,Statement statement){ closeRS(resultSet); closeSt(statement); closeConn(connection); } private static void closeRS(ResultSet resultSet){ try { if(resultSet !=null){ resultSet.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { resultSet = null; } } private static void closeSt(Statement statement){ try { if(statement !=null){ statement.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { statement = null; } } private static void closeConn(Connection connection){ try { if(connection !=null){ connection.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { connection = null; } } }
執行結果:
資料庫表: