package druid; import com.alibaba.druid.pool.DruidDataSource; import java.sql.*; /** * 单例模式-饿汉设计模式 * * @author peanut */ public class ConnectionPool { private static DruidDataSource ds = null; /** * 禁止外部创建对象 */ private ConnectionPool() { } ; //加载时创建 static { //创建一个数据库连接池 ds = new DruidDataSource(); //设置数据库连接驱动 ds.setUrl("jdbc:mysql://localhost:3306/text1?characterEncoding=utf-8&serverTimezone=UTC&useSSL=false"); //设置数据库用户名 ds.setUsername("root"); //设置数据库密码 ds.setPassword("1234"); //初始化数据库连接数,开始连接数为100条 ds.setInitialSize(100); //设置空闲时数据库最小连接数,当目前没有人使用connection连接时,连接池也会有50个待命连接 ds.setMinIdle(50); //设置最大等待时间1分钟,当所有的connection连接都被使用时,在等待获取连接期间最多等待一分钟就会抛出异常 ds.setMaxWait(1000 * 60); //连接池最大连接数,连接池最大连接200个connection ds.setMaxActive(200); } /** * 返回一个连接池方法 目的 是让template连接到数据原 */ public static DruidDataSource getDataSource(){ return ds; } /** * 获取一个connection连接对象 * * @return */ public static Connection getConnection() { synchronized (ConnectionPool.class) { if (ds != null) { try { return ds.getConnection(); } catch (SQLException throwables) { throwables.printStackTrace(); } } return null; } } /** * 关闭连接 * * @param rs * @param st * @param conn * @return */ public static boolean close(ResultSet rs, Statement st, Connection conn , PreparedStatement prepa ) { synchronized (ConnectionPool.class) { try { if (rs != null) { rs.close(); } if (st != null) { st.close(); } if (conn != null) { conn.close(); } if( prepa != null){ prepa.close(); } } catch (SQLException throwables) { throwables.printStackTrace(); return false; } } return true; } }
版权声明:本文为weixin_64773406原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。