JAVA数据库连接池

享元模式

• Connection是Java和数据库两个平行系统的桥梁
• 桥梁构建不易,成本很高,单次使用成本昂贵
• 运用共享技术来实现数据库连接池(享元模式)
—降低系统中数据库连接Connection对象的数量
– 降低数据库服务器的连接响应消耗
– 提高Connection获取的响应速度

第三方数据库连接池

有两种,一种是C3P0,另一种是Druid,
而配置C3P0连接池有两种方式,
一种是直接在程序中配置,
另一种是在XML文件中配置,
同样,配置Druid连接池也有两种方法,
一种是在程序中配置,
另一种在properties文件中配置。

配置创建连接池C3P0:

public class C3p0Factory1 {
	
	private static ComboPooledDataSource dataSource = null;

	public static void init() throws Exception {
		
		dataSource = new ComboPooledDataSource();
		dataSource.setDriverClass( "com.mysql.cj.jdbc.Driver" );            
		dataSource.setJdbcUrl( "jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&serverTimezone=UTC" );
		dataSource.setUser("root");                                  
		dataSource.setPassword("123456");                                  
			
		// the settings below are optional -- c3p0 can work with defaults
		dataSource.setMinPoolSize(5);                                     
		dataSource.setAcquireIncrement(5);
		dataSource.setMaxPoolSize(20);
			
		// The DataSource dataSource is now a fully configured and usable pooled DataSource

	}
	
	public static Connection getConnection() throws Exception {
		if(null == dataSource)
		{
			init();
		}
        return dataSource.getConnection();
    }

}

主类调用:

public class SelectTest {
    public static void main(String[] args){    	
    	  
        Connection conn = null;
        try {
        	//从c3p0获取连接;
            conn = C3p0Factory1.getConnection();
           
            //构建数据库执行者
            Statement stmt = conn.createStatement(); 
            System.out.println("创建Statement成功");      
            
            //执行SQL语句并返回结果到ResultSet
            ResultSet rs = stmt.executeQuery("select bookid, bookname, price from t_book order by bookid");
                        
            //开始遍历ResultSet数据
            while(rs.next())
            {
            	System.out.println(rs.getInt(1) + "," + rs.getString(2) + "," + rs.getInt("price"));
            }
            
            rs.close();
            stmt.close();
            
        } catch (Exception e){
            e.printStackTrace();
        } finally {
        	try	{
        		if(null != conn) {
            		conn.close();
            	}
        	} catch (SQLException e){
                e.printStackTrace();
        	}        	
        }
    }
}

这里要把C3P0和Druid的dependency复制到pom.xml文件中,

com.mchange
c3p0
0.9.5.2



com.alibaba
druid
1.1.10

第二种配置C3P0连接池的方式:

public class C3p0Factory2 {
	
	private static ComboPooledDataSource dataSource = null;

	public static void init() throws Exception {
		
		dataSource = new ComboPooledDataSource();
		//dataSource 自动加载c3p0-config.xml文件
		
		// The DataSource dataSource is now a fully configured and usable pooled DataSource

	}
	
	public static Connection getConnection() throws Exception {
		if(null == dataSource)
		{
			init();
		}
        return dataSource.getConnection();
    }
}

而C3P0的xml文件则配置了连接池各项参数,在程序中只要把文件内容加载就可;

<?xml version="1.0" encoding="UTF-8"?>
<default-config>  <!-- 默认配置 -->
    <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&amp;serverTimezone=UTC</property>
    <property name="user">root</property>
    <property name="password">123456</property>
    <property name="initialPoolSize">5</property>
    <property name="maxPoolSize">20</property>
</default-config>

• driverClass驱动class,这里为mysql的驱动
• jdbcUrljdbc链接
• userpassword数据库用户名密码
• initialPoolSize初始数量:一开始创建多少条链接
• maxPoolSize最大数:最多有多少条链接
• acquireIncrement增量:用完每次增加多少个
• maxIdleTime最大空闲时间:超出的链接会被抛

Druid

这里Druid的配置与C3P0大部分一致;

public class DruidFactory1 {
	private static DruidDataSource dataSource = null;

	public static void init() throws Exception {
		
		dataSource = new DruidDataSource();
		dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); 
		dataSource.setUsername("root");
		dataSource.setPassword("123456");
		dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8&serverTimezone=UTC"); 
		dataSource.setInitialSize(5);
		dataSource.setMinIdle(1); 
		dataSource.setMaxActive(10); 
		// 启用监控统计功能dataSource.setFilters("stat");// 
	}
	
	public static Connection getConnection() throws Exception {//连接池通过此函数与外部连接
		if(null == dataSource)
		{
			init();//执行第9行的函数
		}
        return dataSource.getConnection();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱技术的小小林

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值