第三方数据连接池使用

DBCP

第一步:导包

Commons-dbcp.jar:连接池的实现

Commons-pool.jar:连接池实现的依赖库

<dependency>
    <groupId>commons-dbcp</groupId>
    <artifactId>commons-dbcp</artifactId>
    <version>1.4</version>
</dependency>


<dependency>
    <groupId>commons-pool</groupId>
    <artifactId>commons-pool</artifactId>
    <version>1.6</version>
</dependency>

第二步:构建配置文件

#连接设置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/db_name
username=root
password=123456

#<!-- 初始化连接,:初始有几个连接 -->
initialSize=10

#最大连接数量:连接池最多几个连接
maxActive=50

#<!-- 最大空闲连接,如果空闲的连接过多,就释放多余连接-->
maxIdle=20

#<!-- 最小空闲连接 -->
minIdle=5

#<!-- 超时等待时间以毫秒为单位 60000毫秒/1000等于60秒:如果有线程想获取连接,因为连接池没有连接对象需要等待,等待的最长时间是60s-->
maxWait=60000


#JDBC驱动建立连接时附带的参数的格式必须为这样:[属性名=property;]
#注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们。
connectionProperties=useUnicode=true;characterEncoding=utf8

#指定由连接池所创建的连接的自动提交(auto-commit)状态。
defaultAutoCommit=true

#driver default 指定由连接池所创建的连接的只读(read-only)状态。
#如果没有设置该值,则“setReadOnly”方法将不被调用。(某些驱动并不支持只读模式,如:Informix)
defaultReadOnly=

#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
#可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=REPEATABLE_READ

dbcp.properties

第三步:写一个连接池的工具类

工具类

  public class DBCPUtils {

      public class DBCPUtils {
      
      	static DataSource dataSource;
      
          static {
      
              try {
                  // 读取文件
                  InputStream in = new FileInputStream("dbcp.properties");
      
                  Properties properties = new Properties();
      
                  properties.load(in);
      
                  // 创建一个DBCP的数据源工厂 (数据源就等于连接池)
                  BasicDataSourceFactory dataSourceFactory = new BasicDataSourceFactory();
      
                  // 根据数据源工厂,创建一个数据源
                  dataSource = dataSourceFactory.createDataSource(properties);
      
              } catch (FileNotFoundException e) {
                  e.printStackTrace();
              } catch (IOException e) {
                  e.printStackTrace();
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      
          public static Connection getConnection(){
      
              Connection connection = null;
              try {
                  connection = dataSource.getConnection();
              } catch (SQLException e) {
                  e.printStackTrace();
              }
      
              return connection;
      
          }
      }

第四步:使用

  @Test
  public void testSelectUserById(){
  
      Connection connection = null;
      PreparedStatement preparedStatement = null;
      ResultSet resultSet = null;
  
      try {
  
          // 根据DBCP数据库连接池获取数据源
          connection = DBCPUtils.getConnection();
  
          // 我们去操作数据库
          preparedStatement = connection.prepareStatement("select * from user where id = ?");
  
          preparedStatement.setInt(1, 9992333);
  
          resultSet = preparedStatement.executeQuery();
  
          User user = new User();
  
          if (resultSet.next()) {
  
              user.setId(resultSet.getInt("id"));
              user.setUsername(resultSet.getString("username"));
              user.setPassword(resultSet.getString("password"));
              user.setAge(resultSet.getInt("age"));
          }
  
          System.out.println("user:" + user);
  
  
      }catch (Exception ex) {
          ex.printStackTrace();
      } finally {
          // 关闭资源怎么做呢?
          // 关闭资源可以这么做吗?
          // 我们这个地方,去调用我们connection.close()方法,其实取决于我们这个connection实例对象的close()是怎么写的?
          // 我们作为使用者,在使用完成之后,要求调用我们的connection.close()方法,尽管这个方法可能不是真正的关闭连接,至于到底这个连接关闭了没有,取决于我们数据源实现类本身的策略。
          JDBCUtils.closeSource(connection,preparedStatement,resultSet);
      }
  }

C3P0

1、导包

<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
    <groupId>com.mchange</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.5.4</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.mchange/mchange-commons-java :这个是c3p0针对Java的拓展包-->
<dependency>
    <groupId>com.mchange</groupId>
    <artifactId>mchange-commons-java</artifactId>
    <version>0.2.14</version>
</dependency>

 2. 构建配置文件

一定要是xml文件 

注意,c3p0的配置是有要求的,必须是名字叫做 `c3p0-config.xml`, 路径必须在src目录下

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
    <default-config>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/dbName?useSSL=false&amp;characterEncoding=utf8</property>
        <property name="user">root</property>
        <property name="password">123456</property>

        <!-- 扩容的大小 -->
        <property name="acquireIncrement">5</property>
        <!-- 初始化容量大小 -->
        <property name="initialPoolSize">10</property>
        <!-- 最小多少个连接-->
        <property name="minPoolSize">5</property>
        <!-- 最大多少个连接-->
        <property name="maxPoolSize">20</property>
    </default-config>
</c3p0-config>

---------------------------------------------------------------------------------------------------------------------------------

或者不用配置文件自己手动设置参数信息,硬编码

 3、 写一个连接池的工具类


public class C3p0Utils {

    // 声明一个数据源
    static DataSource dataSource;

    static {
        // 创建数据源
        dataSource = new ComboPooledDataSource();
    }

    public static Connection getConnection(){

        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return connection;

    }
}

4、使用

@Test
    public void testSelectUserById(){

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {

            // 根据c3p0数据库连接池获取数据源 
            connection = C3p0Utils.getConnection();

            // 我们去操作数据库
            preparedStatement = connection.prepareStatement("select * from user where id = ?");

            preparedStatement.setInt(1, 9992333);

            resultSet = preparedStatement.executeQuery();

            User user = new User();

            if (resultSet.next()) {

                user.setId(resultSet.getInt("id"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                user.setAge(resultSet.getInt("age"));
            }

            System.out.println("user:" + user);


        }catch (Exception ex) {
            ex.printStackTrace();
        } finally {

            // 关闭资源怎么做呢?
            // 关闭资源可以这么做吗?
            // 我们这个地方,去调用我们connection.close()方法,其实取决于我们这个connection实例对象的close()是怎么写的?
            // 我们作为使用者,在使用完成之后,要求调用我们的connection.close()方法,尽管这个方法可能不是真正的关闭连接,至于到底
            // 这个连接关闭了没有,取决于我们数据源实现类本身的策略。
            JDBCUtils.closeSource(connection,preparedStatement,resultSet);
        }
    }

Druid

[官方文档](https://github.com/alibaba/druid/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98)

1、导包

<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.19</version>
</dependency>

2、配置文件

 

配置一个properties配置文件

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/29_back2?useSSL=false&characterEncoding=utf8
username=root
password=123456

# 可选的配置项
#初始连接数
#initialSize=10
#最多活跃连接数目
#maxActive=100

3、 写一个连接池的工具类

public class DruidUtils {

    static DataSource dataSource;

    static {
        try {
            // 加载配置
            FileInputStream in = new FileInputStream("druid.properties");
            Properties properties = new Properties();
            properties.load(in);

            // 创建数据源工厂
            DruidDataSourceFactory druidDataSourceFactory = new DruidDataSourceFactory();

            // 创建数据源
            dataSource = druidDataSourceFactory.createDataSource(properties);

        }catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    // 获取连接
    public static Connection getConnection(){

        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return connection;

    }
}

4、使用

public class DruidTest {

    @Test
    public void testSelectUserById(){

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {

            // 根据DBCP数据库连接池获取数据源
            connection = DruidUtils.getConnection();

            // 我们去操作数据库
            preparedStatement = connection.prepareStatement("select * from user where id = ?");

            preparedStatement.setInt(1, 9992333);

            resultSet = preparedStatement.executeQuery();

            User user = new User();

            if (resultSet.next()) {

                user.setId(resultSet.getInt("id"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                user.setAge(resultSet.getInt("age"));
            }

            System.out.println("user:" + user);


        }catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            // 关闭资源怎么做呢?
            // 关闭资源可以这么做吗?
            // 我们这个地方,去调用我们connection.close()方法,其实取决于我们这个connection实例对象的close()是怎么写的?
            // 我们作为使用者,在使用完成之后,要求调用我们的connection.close()方法,尽管这个方法可能不是真正的关闭连接,至于到底
            // 这个连接关闭了没有,取决于我们数据源实现类本身的策略。
            JDBCUtils.closeSource(connection,preparedStatement,resultSet);
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值