首先我们需要知道为什么要使用连接池:因为jdbc没有保持连接的能力,一旦超过一定时间没有使用(大约几百毫秒),连接就会被自动释放掉,每次新建连接都需要140毫秒左右的时间而C3P0连接池会池化连接,随时取用,平均每次取用只需要10-20毫秒,所以如果是很多客户端并发随机访问数据库的话,使用连接池的效率会高。
接下来我们看使用c3p0需要做那些准备:首先需要导入相对应的jar包:c3p0-0.9.1.2-jdk1.3.jar,然后就是链接数据库的配置文件:c3p0-config.xml,配置如下 1 <?xml version="1.0" encoding="UTF-8"?> 2 <c3p0-config> 3 <!-- This is default config! --> 4 <default-config> 5 <property name="initialPoolSize">10</property> 6 <property name="maxIdleTime">30</property> 7 <property name="maxPoolSize">100</property> 8 <property name="minPoolSize">10</property> 9 <property name="maxStatements">200</property>10 </default-config>11 12 <!-- This is my config for mysql-->13 <named-config name="mysql">14 <!-- 加载驱动 -->15 <property name="driverClass">com.mysql.jdbc.Driver</property> 16<!--其中studio为数据库名称-->17 <property name="jdbcUrl">jdbc:mysql://localhost:3306/studio?useUnicode=true&characterEncoding=UTF8</property>18 <!--连接用户名 -->19 <property name="user">root</property> 20<!--连接密码-->21 <property name="password"></property>22 <property name="initialPoolSize">10</property>23 <property name="maxIdleTime">30</property>24 <property name="maxPoolSize">100</property>25 <property name="minPoolSize">10</property>26 <property name="maxStatements">200</property>27 </named-config>28 </c3p0-config> 接下来是c3p0链接数据库的工具类,调用此类之后我们就无需再手动关闭连接,代码如下 1 import java.sql.Connection; 2 import java.sql.PreparedStatement; 3 import java.sql.ResultSet; 4 import java.sql.SQLException; 56 import com.mchange.v2.c3p0.ComboPooledDataSource; 7 public class C3P0Util { 8 static ComboPooledDataSource cpds=null; 9 static{ 10 cpds = new ComboPooledDataSource("mysql");//这是mysql数据库11 }12 /** 13* 获得数据库连接14*/15 public static Connection getConnection(){16 try {17 return cpds.getConnection();18 } catch (SQLException e) {19 e.printStackTrace();20 return null;21 }22 }23 24 /** 25* 数据库关闭操作 26*/27 public static void close(Connection conn,PreparedStatement pst,ResultSet rs){28 if(rs!=null){29 try {30 rs.close();31 } catch (SQLException e) {32 e.printStackTrace();33 }34 }35 if(pst!=null){36 try {37 pst.close();38 } catch (SQLException e) {39 e.printStackTrace();40 }41 }42 43 if(conn!=null){44 try {45 conn.close();46 } catch (SQLException e) {47 e.printStackTrace();48 }49 }50 }51 } 最后我们只需要在自己写的Dao层操作中获取到C3p0的连接就好了,这里我就只写一个查询的方法public List<String> getSelect() {
// sql语句
String sql = "select * from user";
// 获取到连接
Connection conn = C3P0Util.getConnection();
PreparedStatement pst = null;
// 定义一个list用于接受数据库查询到的内容
List<String> list = new ArrayList<String>();
try {
pst = (PreparedStatement) conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
while (rs.next()) {
// 将查询出的内容添加到list中,其中userName为数据库中的字段名称
list.add(rs.getString("userName"));
}
} catch (Exception e) {
}
return list;
} 主要是第5行中获取链接的方式改变了,当然我们既然链接数据库就需要导入相对应的jar包本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-11/136613.htm