一、引入jar包
二、java代码
1 @Test 2 public void testXML() throws Exception { 3 // 创建c3p0连接池核心工具类 4 // 自动加载src下c3p0的配置文件【c3p0-config.xml】 5 ComboPooledDataSource dataSource = new ComboPooledDataSource();// 使用默认的配置 6 PreparedStatement pstmt = null; 7 8 // 获取连接 9 Connection con = dataSource.getConnection(); 10 for (int i=1; i<11;i++){ 11 String sql = "insert into employee(empName,dept_id) values(?,?)"; 12 // 执行更新 13 pstmt = con.prepareStatement(sql); 14 pstmt.setString(1, "Rose" + i); 15 pstmt.setInt(2, 1); 16 pstmt.executeUpdate(); 17 } 18 pstmt.close(); 19 // 关闭 20 con.close(); 21 22 }
三、配置文件(c3p0-config.xml)
1 <c3p0-config> 2 <default-config> 3 <property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbc_demo 4 </property> 5 <property name="driverClass">com.mysql.jdbc.Driver</property> 6 <property name="user">root</property> 7 <property name="password">root</property> 8 <property name="initialPoolSize">3</property> 9 <property name="maxPoolSize">6</property> 10 <property name="maxIdleTime">1000</property> 11 </default-config> 12 13 14 <named-config name="oracle_config"> 15 <property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbc_demo</property> 16 <property name="driverClass">com.mysql.jdbc.Driver</property> 17 <property name="user">root</property> 18 <property name="password">root</property> 19 <property name="initialPoolSize">3</property> 20 <property name="maxPoolSize">6</property> 21 <property name="maxIdleTime">1000</property> 22 </named-config> 23 24 25 </c3p0-config>
四、JdbcUtils(使用连接池)
1 public class JdbcUtil { 2 3 //初始化连接池 4 private static DataSource dataSource; 5 6 //静态代码块初始化连接池资源,只执行一次 7 static{ 8 dataSource = new ComboPooledDataSource(); 9 } 10 11 /** 12 * 返回连接对象 13 */ 14 public static Connection getConnection() { 15 try { 16 return dataSource.getConnection(); 17 } catch (SQLException e) { 18 throw new RuntimeException(e); 19 } 20 } 21 22 /** 23 * 关闭 24 */ 25 public static void closeAll(Connection con, Statement stmt, ResultSet rs) { 26 try { 27 if (rs != null) { 28 rs.close(); // 快速异常捕获 Alt + shift + z 29 rs = null; // 建议垃圾回收期回收资源 30 } 31 if (stmt != null) { 32 stmt.close(); 33 stmt = null; 34 } 35 if (con != null && !con.isClosed()) { 36 con.close(); 37 con = null; 38 } 39 } catch (SQLException e) { 40 throw new RuntimeException(e); 41 } 42 } 43 }
时间: 2024-12-28 09:06:57