package com.tedu.jt.utils; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.mchange.v2.c3p0.ComboPooledDataSource; /** * JDBC工具類 */ public class JDBCUtils { /** * 2.創(chuàng)建c3p0連接池實例 */ private static ComboPooledDataSource pool = new ComboPooledDataSource(); /** * 1.私有化構(gòu)造函數(shù) */ private JDBCUtils() {} /** * 3.提供getConn方法, 用于從連接池中獲取一個連接對象 * @return Connection 連接對象 * @throws Exception */ public static Connection getConn() throws Exception { try { return pool.getConnection(); } catch (SQLException e) { e.printStackTrace(); throw e; } } /** * 4.提供close方法, 用于釋放資源 * @param conn 連接對象 * @param ps 傳輸器對象 * @param rs 結(jié)果集對象 */ public static void close(Connection conn, Statement stat, ResultSet rs) { if(rs != null ){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); }finally{ rs = null; } } if(stat != null ){ try { stat.close(); } catch (SQLException e) { e.printStackTrace(); }finally{ stat = null; } } if(conn != null ){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); }finally{ conn = null; } } } } |
|