11.7

package com.bean;

import com.alibaba.druid.pool.DruidDataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class DBUtil {
// 单例连接池(避免重复创建)
private static DruidDataSource dataSource;

static {
    // 初始化连接池
    dataSource = new DruidDataSource();
    dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://localhost:3306/project_management?useSSL=false&serverTimezone=UTC");
    dataSource.setUsername("root"); // 替换为你的MySQL用户名
    dataSource.setPassword("123456"); // 替换为你的MySQL密码
    dataSource.setInitialSize(5); // 初始连接数
    dataSource.setMaxActive(10); // 最大连接数
}

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

// 关闭连接(归还到连接池)
public static void closeConnection(Connection conn) {
    if (conn != null) {
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

}

posted @ 2025-11-10 17:03  Cx330。  阅读(2)  评论(0)    收藏  举报