数据库连接池
Druid连接池
1、在程序初始化时,预先创建指定数量的数据库连接对象存储在池中。当需要连接数据库时,从连接池中取出现有连接;使用完毕后,也不会进行关闭,而是放回池中,实现复用,节省资源。
2、作用:数据库连接池只用来管理连接。
3、只需要三步 导包 配置文件 加载配置文件
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/companydb?useUnicode=true&characterEncoding=utf8
username=root
password=a123456
#初始化连接
initialSize=10
#最大连接数量
maxActive=50
#最小空闲连接 当前最少保证有多少个连接是空闲的
minIdle=5
#超时等待 时间以毫秒为单位
maxWait=5000
#还有很多配置
private static Properties properties = new Properties();
private static DruidDataSource dataSource = null;
private static ThreadLocal<Connection> tl = new ThreadLocal<>(); //本地化线程 在线程中创建一个map 用于事务的相关操作
static {
try {
properties.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
//连接数据库的方法
public static Connection getConnection(){
Connection connection = tl.get();
try {
if (connection == null){
connection = dataSource.getConnection();
tl.set(connection);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return tl.get();
}
//事务提交由自动变为手动
public static void begin(){
Connection connection = getConnection();
try {
//开启事务
connection.setAutoCommit(false);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
//提交
public static void commit(){
try {
getConnection().commit();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
close(getConnection(),null,null);
}
}
//回滚
public static void rollback(){
try {
getConnection().rollback();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
close(getConnection(),null,null);
}
}
//关闭连接
public static void close(Connection connection, Statement statement, ResultSet resultSet){
if (resultSet!= null){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (statement !=null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection!= null){
try {
if (tl.get()!=null){
//关闭连接前先删除存储在集合中的连接
tl.remove();
}
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
浙公网安备 33010602011771号