阿里druid数据库连接及配置文件

本文介绍了一个基于Druid连接池的Java类实现,通过单例模式管理数据库连接。详细展示了如何从配置文件加载数据库参数,并使用DruidDataSource创建数据库连接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class JDBCDruid {
     
    private static Properties properties;
    private static  JDBCDruid druid;
    private static DruidDataSource ds;
     
    //静态代码块加载配置文件 
    static {
        properties=new Properties();
        try {
            properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("druid.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 创建单列模式
     * @return JDBCDruid实例
     */
    public static synchronized JDBCDruid getInstance() {
        if(druid==null) {
            druid=new JDBCDruid();
            return druid;
        }
        return druid;
    }
     
    private JDBCDruid() {
 
        ds=new DruidDataSource();
        ds.setDriverClassName(properties.getProperty("driverClassName"));
        ds.setUrl(properties.getProperty("url"));
        ds.setUsername(properties.getProperty("username"));
        ds.setPassword(properties.getProperty("password"));
        ds.setMaxActive(Integer.parseInt(properties.getProperty("maxActive")));
         
         
    }
     
     
      public  Connection getConnection() throws SQLException {
          Connection connection = ds.getConnection();
          return connection;
      }
      
 
}

下面是druid.properties文件的配置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/mybase
username=root
password=abc123
initialSize=5
maxActive=10
maxWait=3000
maxIdle=8
minIdle=3

拿去白嫖吧,记得点个赞哦 谢谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值