zoukankan      html  css  js  c++  java
  • JavaJDBC【六、连接池】

    背景

    1、连接是一种重要资源
    2、频繁连接数据库会增加数据库压力

    常用连接池

    dbcp

    1、导入jar包(官网下载)
    commons-dbcp.jar
    commons-pool.jar
    commons-logging.jar
    2、配置
    dbcp.properties
    ![](http://images2015.cnblogs.com/blog/692906/201704/692906-20170406081212363-330328016.png)
    3、用配置创建DataSource
    Properties p = new Properties();
    p.load(Object.class.getResourceAsStream("fileName");
    DataSource ds = BasicDataSourceFactory.createDataSource(p);
    4、用DataSource获取连接
    Connection con = ds.getConnection();
    

    Demo:

    public class DBCPUtil {
    private static DataSource DS;
    private static final String config = "/dbcp.properties";
    
    public DBCPUtil() {
    	initDBCP();
    }
    
    private static void initDBCP() {
    	Properties ppts = new Properties();
    	try {
    		ppts.load(Object.class.getResourceAsStream(config));
    		DS = BasicDataSourceFactory.createDataSource(ppts);
    	} catch (IOException e) {
    		e.printStackTrace();
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    }
    
    public Connection GetConnection() {
    	Connection con = null;
    	try {
    		if (DS != null) {
    			con = DS.getConnection();
    		}
    	} catch (SQLException e) {
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    	}
    	return con;
    }
    }
    

    c3p0

    1、导入jar包(官网下载)
    c3p0.jar
    mchange-commons.jar
    2、配置
    c3p0.properties![](http://images2015.cnblogs.com/blog/692906/201704/692906-20170407082502113-1572894078.png)
    3、创建DataSource
    ComboPooledDataSource DS = new ComboPooledDataSource();
    4、用DataSource获取连接
    Connection con = DS.getConnection();
    

    Demo:

    public class C3P0Util {
    private static ComboPooledDataSource DS = new ComboPooledDataSource();
    
    public static Connection GetConnection() throws SQLException {
    	Connection con = DS.getConnection();
    	return con;
    }
    }
    

    差异

  • 相关阅读:
    第10组 Alpha冲刺 (4/6)(组长)
    Android菜鸟成长记10 ListVew
    Android菜鸟成长记3activity类
    Android菜鸟成长记2内部类
    Android菜鸟成长记7 Android的五大布局
    Android菜鸟成长记4button点击事件
    Android菜鸟成长记8 布局实践(微信界面的编写)
    Android菜鸟成长记9 selector的用法
    Android菜鸟成长记6 网络连接的检查
    Android菜鸟成长记5ADB和sqllite
  • 原文地址:https://www.cnblogs.com/shanelau/p/6671494.html
Copyright © 2011-2022 走看看