Simple database connection pool

Simple database connection pool

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.ResourceBundle;

@Component
public class JdbcUtils {

private static String greenplum_driver;
private static String greenplum_url;
private static String greenplum_user;
private static String greenplum_password;
private LinkedList<Connection> dataSources=new LinkedList<Connection>();


static {
    greenplum_driver = ResourceBundle.getBundle("gpDb").getString("greenplum_driver");
    greenplum_url = ResourceBundle.getBundle("gpDb").getString("greenplum_url");
    greenplum_user = ResourceBundle.getBundle("gpDb").getString("greenplum_user");
    greenplum_password = ResourceBundle.getBundle("gpDb").getString("greenplum_password");
}


public  JdbcUtils() {
    try {
        //加载驱动
        Class.forName(greenplum_driver);
        //装载驱动
        //循环创建5个连接并放入连接池
        for (int i = 0; i < 10; i++) {
            Connection con = DriverManager.getConnection(greenplum_url, greenplum_user, greenplum_password);
            dataSources.add(con);
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    }

}
//取出连接池中一个连接

public Connection getConnection() throws SQLException {
    Connection conn=null;
    if(dataSources.size()>0){
        conn = dataSources.removeFirst(); // 删除第一个连接返回
    }else{
        Connection con = DriverManager.getConnection(greenplum_url, greenplum_user, greenplum_password);
        conn =con;
    }
    return conn;
}

//将连接放回连接池
public void releaseConnection(Connection conn) {
    if(dataSources.size()<10) {
        dataSources.add(conn);
    }else{
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

}

Released four original articles · won praise 1 · views 123

Guess you like

Origin blog.csdn.net/chaouyany/article/details/105054980