当前位置: 首页 > article >正文

Druid 连接池工具类及其在企业级应用中的实践

在现代企业级应用中,数据库连接池是提升系统性能和稳定性的关键技术之一。Druid 是阿里巴巴开源的一款高性能数据库连接池,广泛应用于各种 Java 项目中。本文将结合代码示例,深入探讨如何封装 Druid 连接池为工具类,并分析其在实际企业级应用中的最佳实践。

1. Druid 连接池工具类的设计

1.1 工具类的作用

工具类的主要目的是封装重复性代码,提供简洁的 API 供其他模块调用。对于 Druid 连接池,工具类可以封装以下功能:

  • 初始化连接池。

  • 提供获取连接的方法。

  • 提供关闭资源的方法

1.2 工具类的实现

以下是一个典型的 Druid 连接池工具类实现:

package untils;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DruidUtils_ {

    private static DataSource ds;

    static {
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("src\\myDruid.properties"));
            ds = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 获取数据库连接
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    // 关闭资源
    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);
        }
    }
}

 

2. 工具类的核心功能

2.1 初始化连接池

在静态代码块中,工具类通过加载配置文件 druid.properties 初始化 Druid 连接池

static {
    Properties properties = new Properties();
    try {
        properties.load(new FileInputStream("src\\myDruid.properties"));
        ds = DruidDataSourceFactory.createDataSource(properties);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

2.2 获取连接

通过 getConnection 方法,工具类提供获取数据库连接的接口:

public static Connection getConnection() throws SQLException {
    return ds.getConnection();
}

2.3 关闭资源

通过 close 方法,工具类封装了关闭 ResultSetStatement 和 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);
    }
}

3. 工具类的使用示例

3.1 查询数据

以下是一个使用工具类查询数据库的示例:

 @Test
    public void  test_Druid(){
        //        得到connect,preparedStatement先初始化 ,注意代码的规范性
        Connection conn = null;
        PreparedStatement preparedStatement =null;
        ResultSet resultSet= null;

        Scanner sc = new Scanner(System.in);
        System.out.println("请输入要查询的人名:");
        String s = sc.nextLine();

        //        组织sql语言   //  ? 不能用于表名或数据库名的占位符,PreparedStatement 仅支持参数化 列值,不支持表名、数据库名等结构化对象的动态替换。
        String  sql="select * from sql_injection where name=?";


        try {
            conn = DruidUtils_.getConnection();  //利用静态库实现connection
            preparedStatement = conn.prepareStatement(sql);
            preparedStatement.setString(1,s);
            resultSet = preparedStatement.executeQuery();

            while (resultSet.next()){
                String name = resultSet.getString(1);
                String pwd = resultSet.getString(2);
                System.out.println(name+"\t"+pwd);

            }
        } catch (SQLException e) {
//            throw new RuntimeException(e);
            e.printStackTrace();
        }finally {
//            关闭资源
            DruidUtils_.close(resultSet,preparedStatement,conn);  //利用静态库与实现close();
        }


    }

3.2 插入数据

以下是一个使用工具类插入数据的示例:

import untils.DruidUtils_;
import java.sql.Connection;
import java.sql.PreparedStatement;

public class Main {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement statement = null;

        try {
            connection = DruidUtils_.getConnection();
            String sql = "INSERT INTO users (username, password) VALUES (?, ?)";
            statement = connection.prepareStatement(sql);
            statement.setString(1, "admin");
            statement.setString(2, "123456");
            int rows = statement.executeUpdate();
            System.out.println("插入行数: " + rows);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DruidUtils_.close(null, statement, connection);
        }
    }
}

5. 总结

通过封装 Druid 连接池为工具类,可以显著提升代码的复用性和可维护性。Druid 连接池凭借其高性能、强大的监控功能和丰富的扩展性,成为企业级应用中的首选数据库连接池。希望本文的内容能帮助您更好地理解和使用 Druid 连接池工具类。


http://www.kler.cn/a/591586.html

相关文章:

  • Linux IP 配置
  • QT 学习笔记2
  • win/linux开机启动exe程序
  • AT指令集-NBIOT
  • 明基PD2700U显示器无法调节图像模式
  • Qt窗口控件之字体对话框QFontDialog
  • 【css酷炫效果】纯CSS实现进度条加载动画
  • Go 语言 `map` 详解
  • 凸优化算法学习笔记:闵可夫斯基和与Slope trick
  • 在k8s中利用Helm部署Prometheus+Grafana和Loki日志系统
  • 什么是时序数据库?
  • mybatis_plus的乐观锁
  • 有了大语言模型还需要 RAG 做什么
  • windows下使用vscode+cline插件体验MCP,体验使用AI控制浏览器,踩坑记录(至少让你节省3个小时弯路版)(喂饭级别)
  • 【第九节】windows sdk编程:通用控件的使用
  • Pygame实现记忆拼图游戏8
  • PHP转GO Go语言环境搭建(Day1) 常见问题及解决方案指南
  • Ubuntu24.04安装ROS2 Jazzy
  • ubuntu下TFTP服务器搭建
  • 宝塔docker切换存储目录