【java学习资料】Druid 连接池

Druid jar包下载地址:https://mvnrepository.com/search?q=druid
Druid properties配置文件:

# druid.properties文件的配置
driverClassName=com.mysql.cj.jdbc.Driver
#批处理需要在url后加上这句话 ?rewriteBatchedStatements=true
url=jdbc:mysql://127.0.0.1:3306/db02?rewriteBatchedStatements=true
# 数据库用户
username=root
#数据库密码
password=
# 初始化连接数量
initialSize=10
# 最小连接数
midIdle=5
# 最大连接数
maxActive=50
# 最大超时时间
maxWait=3000


语法:

package com.jdbc_.druid_;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.util.Properties;

public class Druid_ {
    public static void main(String[] args) throws Exception {

        //1、在libs目录下加入druid包
        //2、在src目录下加入配置文件 druid.properties
        //3、创建properties对象,读取配置文件
        Properties properties = new Properties();
        properties.load(new FileInputStream("src/druid.properties"));

        //4、创建一个指定参数的数据库连接池
        DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);

        //5、连接
        Connection connection = dataSource.getConnection();

        System.out.println("连接成功。。进行数据操作。。。");

        //关闭
        connection.close();
    }
}


Druid工具类

public class JDBCDruidUtils {

    private static DataSource dataSource = null;

    static {
        try {
            Properties properties = new Properties();
            properties.load(new FileInputStream("src/druid.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //得到连接
    public static Connection getConnection() {
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return connection;
    }

    //关闭连接,在数据库连接池中,close不是真的断开连接,只是把connection对象放回连接池
    public static void close(ResultSet resultSet, Statement statement, Connection connection) {

        try {
            if (resultSet != null) {
                resultSet.close();
            }

            if (statement != null) {
                statement.close();
            }

            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值