欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c3p0 连接池使用

程序员文章站 2022-07-06 15:27:22
文章目录1. 导入依赖2. 编写配置文件1. 导入依赖 com.mchange c3p0 0.9.2 2. 编写配置文件package com.beyond.nothing.util...

1. 导入依赖

  <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.2</version>
    </dependency>

2. 编写配置文件

package com.beyond.nothing.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.beans.PropertyVetoException;
import java.sql.*;

public class JDBCUtil {
    private static final String USERNAME = "root";
    private static final String PWD = "210374520";
    private static final String URL = "jdbc:mysql://localhost:3308/thedemo";
    private static final String DRIVER = "com.mysql.jdbc.Driver";

    // 使用 c3p0 连接池
    private static final ComboPooledDataSource datasource = new ComboPooledDataSource();

    static {
//        // 注册驱动
//        try {
//            Class.forName(DRIVER);
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        }
       try {
           datasource.setUser(USERNAME);
           datasource.setPassword(PWD);
           datasource.setJdbcUrl(URL);
           datasource.setDriverClass(DRIVER);
       }catch (PropertyVetoException e){
           e.printStackTrace();
       }

        // 设置最大连接数
        datasource.setMaxPoolSize(10);
        // 设置最低保持的连接数
        datasource.setMinPoolSize(5);

    }


    public static Connection getCoon() throws SQLException {
//        return DriverManager.getConnection(URL,USERNAME,PWD);
        return datasource.getConnection();
    }


    public static void main(String[] args) throws SQLException {
        Connection coon = getCoon();
        System.out.println(coon.toString());
    }

    public static void close(ResultSet resultSet, PreparedStatement preparedStatement, Connection connection) {
        try {
            if (null != resultSet){
                resultSet.close();
            }
            if (null != preparedStatement){
                preparedStatement.close();
            }
            if (null != connection){
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

本文地址:https://blog.csdn.net/Beyond_Nothing/article/details/112586046