JDBC—数据库连接池工具

本文详细介绍了数据库连接池的概念,重点关注了阿里巴巴的Druid和C3P0两个连接池工具的使用。对于Druid,讲解了其配置文件的加载和DataSource的获取,以及与普通JDBC获取连接的对比。而对于C3P0,文章阐述了配置文件的编写、工具类的创建和使用步骤,并列举了C3P0的一些关键配置参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

数据库连接池


一. Druid

JDBC 的数据库连接池使用 javax.sql.DataSource 来表示,DataSource 只是一个接口,该接口通常由服务器(Weblogic, WebSphere, Tomcat)提供实现,也有一些开源组织提供实现。

Druid(德鲁伊)是阿里巴巴开源平台上一个数据库连接池实现,它结合了C3P0、DBCP、Proxool等DB池的优点,同时加入了日志监控,可以很好的监控DB池连接和SQL的执行情况,可以说是针对监控而生的DB连接池,据说是目前最好的连接池。

1.Druid连接池的使用

步骤:

  • 1.加载Druid配置文件
  • 2.获取 DataSource数据源:DruidDataSourceFactory.createDataSource(properties)
  • 3.获取数据库连接 Connection:datasource.getConnection();
  • 4.执行增删改查
  • 5.释放资源

对比,普通JDBC获取连接的步骤:

  • 1.加载并注册驱动:Class.forName(“com.mysql.jdbc.Driver”);
  • 2.获取连接资源:DriverManager.getConnection(url, properties);
  • 3.进行增删改查:statement.executeQuery()/executeUpdate(); PrepareStatement…
  • 4.释放资源:resultSet.close();/statement.close();/connection.close;

案例:

package com.mytest.druid;

import java.sql.Connection;
import java.util.Properties;
import javax.sql.DataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

public class TestDruid {
	public static void main(String[] args) throws Exception {
		Properties pro = new Properties();
		//1.加载Druid配置文件
		pro.load(TestDruid.class.getClassLoader().getResourceAsStream("druid.properties"));
		//2.获取 DataSource
		DataSource ds = DruidDataSourceFactory.createDataSource(pro);
		//3.获取数据库连接
		Connection conn = ds.getConnection();
		System.out.println(conn);
		//4.释放资源
		conn.close();
	}
}

2.Druid配置文件

德鲁伊配置文件参数

二. C3P0连接池

1.C3P0连接池工具类编写

C3P0开源免费的连接池!目前使用它的开源项目有:Spring、Hibernate等。使用C3P0连接池需要导入jar包,c3p0使用时还需要添加配置文件“c3p0-config.xml”

使用步骤

  1. 添加jar包
  2. 编写配置文件 c3p0-config.xml,放在src中(注:文件名一定不要写错)
  3. 编写工具类
1)编写配置文件 c3p0-config.xml
 <c3p0-config>
   <!-- 使用默认的配置读取连接池对象 -->
   <default-config>
     <!--  连接参数 -->
     <property name="driverClass">com.mysql.jdbc.Driver</property>
     <property name="jdbcUrl">jdbc:mysql://localhost:3306/test</property>
     <property name="user">root</property>
     <property name="password">root</property>

     <!-- 连接池参数 -->
     <property name="initialPoolSize">5</property>
     <property name="maxPoolSize">10</property>
     <property name="checkoutTimeout">2000</property>
     <property name="maxIdleTime">1000</property>
   </default-config>
 </c3p0-config>

c3p0连接池常用的配置参数:

参数说明
initialPoolSize初始连接数
maxPoolSize最大连接数
checkoutTimeout最大等待时间
maxIdleTime最大空闲回收时间

初始连接数:刚创建好连接池的时候准备的连接数量
最大连接数:连接池中最多可以放多少个连接
最大等待时间:连接池中没有连接时最长等待时间
最大空闲回收时间:连接池中的空闲连接多久没有使用就会回收

2)编写C3P0工具类
public class JdbcUtils {
    //1.创建一个C3P0的连接池对象(使用c3p0-config.xml中default-config标签中对应的参数)
    public static DataSource ds = new ComboPooledDataSource();

    //2.从池中获得一个连接
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    //3.释放资源
    public static void closeAll(ResultSet rs, Statement stmt, Connection conn){
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            rs = null;
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            stmt = null;
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            conn = null;
        }
    }
}

2. C3P0连接池工具类的使用

public class Demo {
	public static void main(String[] args) throws Exception {
		// 拿到连接
		Connection conn = JdbcUtils.getConnection();

		// 执行sql语句
		String sql = "INSERT INTO student VALUES (NULL, ?, ?, ?);";
		PreparedStatement pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, "李四");
		pstmt.setInt(2, 30);
		pstmt.setDouble(3, 50);
		int i = pstmt.executeUpdate();
		System.out.println("影响的函数: " + i);

		// 关闭资源
		JdbcUtils.close(conn, pstmt);
	}
}

三.创建数据库连接工具类

/**
 * 用于获取连接和释放连接的工具类,使用Druid
 * @author ZhengXuanYi
 */
public class JDBCUtils {
	private static DataSource dataSource;
	
	//1.初始化德鲁伊数据库连接池
	static {
		try {
			//1、读取druip.properties文件
			Properties pro = new Properties();
			pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
			
			//2、获取数据源
			dataSource = DruidDataSourceFactory.createDataSource(pro);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	//2.获取连接
	public static Connection getConnection() {
		Connection connection = null;
		try {
			connection = dataSource.getConnection();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return connection;
	}

	//3.释放连接
	public static void releaseConnection(Connection connection) {
		if(connection != null) {
			try {
				connection.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值