连接池

1、c3p0连接池

jar包:

  使用c3p0连接池:

package cn.getword.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 获取连接,Connection是代理对象,close被重写了,不是真正的关闭连接,而是放回连接池中
 *
 */
public class MySqlPool {
    private static final String DRIVER="";
    private static final String URL="";
    private static final String USRNAME="";
    private static final String PASSWORD="";
    private static ComboPooledDataSource dataSource;
    static {
        dataSource =new ComboPooledDataSource();
        try {
            dataSource.setDriverClass("");
            dataSource.setJdbcUrl("");
            dataSource.setUser("");
            dataSource.setPassword("");

            //配置连接池相关的参数
            dataSource.setMaxPoolSize(5);
            dataSource.setMinPoolSize(2);
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
    }
    private MySqlPool(){}
    private static final MySqlPool INSTANCE = new MySqlPool();
    public static MySqlPool getInstance(){
        return INSTANCE;
    }

    //连接只能一个一个取
    public synchronized Connection getConnection() throws SQLException {
        Connection connection = null;
        connection = dataSource.getConnection();
        return connection;
    }

}
View Code

  这里的close并不是真的关闭连接,而是放回连接池中。因此,使用完后必须 close。

  如果连接池中的连接全部被取出,那么有人再次取出时,就会等待

 

2.Spring的JdbcTemplate

org.springframework.jdbc.core.JdbcTemplate;

    public List<User> findAll() {
        return jdbcTemplate.query("select * from t_user", ParameterizedBeanPropertyRowMapper.newInstance(User.class));
    }

 

 

 

 

 

end

posted @ 2018-09-13 16:33  fight139  阅读(97)  评论(0编辑  收藏  举报