layout: post
title: C3P0连接池
subtitle: 例子demo
date: 2018-04-09
author: ZL
header-img: img/20180409.jpg
catalog: true
tags:
- C3P0
- 连接池
这个连接池的作用是减少性能消耗,连接数据库过多会消耗一定的性能
demo代码下载连接:http://ovoz7yxxg.bkt.clouddn.com/C3P0.rar.
-
代码很简单,就是需要配置一些东西,首先导包:
- 第一个:c3p0的包
- 第二个+第三个:Test的包,需要这两个包才可以test运行,而不需要main运行了。
- 第四个:连接数据库的包
-
配置文件,c3p0支持xml和properties两种配置文件,这里介绍xml形式的配置文件(不要更改xml文件的名字c3p0-config.xml)
<?xml version="1.0" encoding="UTF-8"?> <c3p0-config> <default-config> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/test01</property> <property name="user">root</property> <property name="password">123456</property> <property name="initialPoolSize">5</property> <property name="maxPoolSize">20</property> </default-config> <named-config name="zlei"> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql:///test01</property> <property name="user">root</property> <property name="password">123456</property> </named-config> </c3p0-config>
-
java代码
import com.mchange.v2.c3p0.ComboPooledDataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; public class Test { @org.junit.Test public void test(){ Connection conn = null; PreparedStatement preparedStatement = null; //参数:加载c3p0-config.xml里面的哪一个configuration, //如果为空:default-config //不为空的话,则加载 named-config name="zlei" ComboPooledDataSource dataSource = new ComboPooledDataSource("zlei"); try { conn = dataSource.getConnection(); String sql = "insert into tbl_user value(?,?);"; preparedStatement = conn.prepareStatement(sql); preparedStatement.setString(1,"www"); preparedStatement.setString(2,"222"); int rows = preparedStatement.executeUpdate(); if (rows>0){ System.out.println("成功"); } } catch (SQLException e) { e.printStackTrace(); }finally { if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
- 运行结果
这个表后面的两个www,222就是运行了两次以后添加的2个数据,前三个数据时本来就有的