最常用的连接池技术,Spring默认支持c3p0连接池。
核心类
1. CombopooledDataSource ds;
引入,c3p0的jar包
2.使用链接池,创建链接
a)硬编码方式
public void testCode() throws Exception{ //创建连接池工具类 ComboPooledDataSource dataSource = new ComboPooledDataSource(); //设置连接参数 dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/learnstruts"); dataSource.setDriverClass("com.mysql.jdbc.Driver"); dataSource.setUser("root"); dataSource.setPassword("33269456.cx"); dataSource.setInitialPoolSize(3); dataSource.setMaxPoolSize(6); //取得链接对象 java.sql.Connection connection = dataSource.getConnection(); connection.prepareStatement("DELETE FROM user WHERE userId = ‘1‘").executeUpdate(); //关闭 connection.close(); }
b)xml配置方式
c3p0-config.xml
<c3p0-config> <default-config> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/learnstruts</property> <property name="user">root</property> <property name="password">33269456.cx</property> <property name="initialPoolSize">5</property> <property name="maxPoolSize">10</property> </default-config> <!-- <named-config name="oracleConfig"> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql:///day17</property> <property name="user">root</property> <property name="password">root</property> <property name="initialPoolSize">5</property> <property name="maxPoolSize">10</property> </named-config> --> </c3p0-config>
@Test public void testXML() throws Exception{ //在这个类会自动加载src下的c3p0配置文件 ComboPooledDataSource dataSource = new ComboPooledDataSource(); Connection connection = dataSource.getConnection(); connection.prepareStatement("DELETE FROM user WHERE userId = ‘1‘"); connection.close(); }
JdbcUtil.javpackage com.cx.utils;
import javax.sql.DataSource; import org.apache.commons.dbutils.QueryRunner; import com.mchange.v2.c3p0.ComboPooledDataSource; public class JdbcUtils { //初始化连接池 private static DataSource dataSource; //静态代码块加载连接池,只加载一次 static { //从连接池中拿到数据源 dataSource = new ComboPooledDataSource(); } //封装常用对象 public static DataSource getDataSource() { return dataSource; } public static QueryRunner getQueryRunner() { return new QueryRunner(dataSource); } }
时间: 2024-11-03 17:21:06