JDBC 工具类模板
1 package com.itheima.sh.utils; 2 3 import com.mchange.v2.c3p0.ComboPooledDataSource; 4 5 import javax.sql.DataSource; 6 import java.sql.Connection; 7 import java.sql.ResultSet; 8 import java.sql.Statement; 9 10 /* 11 * jdbc工具类 12 */ 13 public class JDBCUtils { 14 //创建c3p0核心类对象 15 private static ComboPooledDataSource cpds = new ComboPooledDataSource(); 16 // 定义一个静态方法对外提供连接 17 public static Connection getConnection() { 18 try { 19 //从c3p0数据库连接池获取连接 20 Connection conn = cpds.getConnection(); 21 return conn; 22 } catch (Exception e) { 23 throw new RuntimeException(e); 24 } 25 } 26 //定义一个静态方法让外界获取数据库连接池对象 27 public static DataSource getDataSource() 28 { 29 return cpds; 30 } 31 32 // 定义一个静态方法让外界关闭资源 33 public static void release(Connection conn, Statement st, ResultSet rs) { 34 try { 35 // 关闭资源 36 if (conn != null) { 37 38 conn.close(); 39 } 40 } catch (Exception e) { 41 // TODO Auto-generated catch block 42 e.printStackTrace(); 43 } 44 try { 45 // 关闭资源 46 if (st != null) { 47 st.close(); 48 } 49 } catch (Exception e) { 50 // TODO Auto-generated catch block 51 e.printStackTrace(); 52 } 53 try { 54 // 关闭资源 55 if (rs != null) { 56 rs.close(); 57 } 58 } catch (Exception e) { 59 // TODO Auto-generated catch block 60 e.printStackTrace(); 61 } 62 } 63 }