JDBC獲取連接、關閉連接的簡單工具類

  1. import java.sql.Connection;  
  2. import java.sql.DriverManager;  
  3. import java.sql.ResultSet;  
  4. import java.sql.SQLException;  
  5. import java.sql.Statement;  
  6.   
  7. public final class JdbcUtils {  
  8.     private static String url = "jdbc:mysql://localhost:3306/jdbc";  
  9.     private static String user = "root";  
  10.     private static String password = "";  
  11.   
  12.     private JdbcUtils() {  
  13.     }  
  14.   
  15.     static {  
  16.         try {  
  17.             Class.forName("com.mysql.jdbc.Driver");  
  18.         } catch (ClassNotFoundException e) {  
  19.             throw new ExceptionInInitializerError(e);  
  20.         }  
  21.     }  
  22.   
  23.     public static Connection getConnection() throws SQLException {  
  24.         return DriverManager.getConnection(url, user, password);  
  25.     }  
  26.   
  27.     public static void free(ResultSet rs, Statement st, Connection conn) {  
  28.         try {  
  29.             if (rs != null)  
  30.                 rs.close();  
  31.         } catch (SQLException e) {  
  32.             e.printStackTrace();  
  33.         } finally {  
  34.             try {  
  35.                 if (st != null)  
  36.                     st.close();  
  37.             } catch (SQLException e) {  
  38.                 e.printStackTrace();  
  39.             } finally {  
  40.                 if (conn != null)  
  41.                     try {  
  42.                         conn.close();  
  43.                     } catch (SQLException e) {  
  44.                         e.printStackTrace();  
  45.                     }  
  46.             }  
  47.         }  
  48.     }  
  49. }  

發佈了14 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章