Driud——数据库连接池的使用

Druid数据库连接池的使用

  1、 导入 jar 包

    jar包下载:Central Repository: com/alibaba/druid/1.1.12 (maven.org)

    

 

 

       导入项目中:(复制进项目后右键-添加为库-项目库)

    

 

 

 

   2、 定义配置文件

    在 src 目录下创建名为 druid.properties 配置文件

    并添加如下配置信息:(其中url、username、password 要根据自身的数据库信息配置,路径设置要正确)

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/db_0915?useSSL=false&useServerPrepStmts=true
username=root
password=1234
# 初始化连接数量
initialSize=5
# 最大连接数
maxActive=10
# 最大等待时间
maxWait=3000

   

  3、 加载配置文件(文件输入流内的地址需根据自身项目中的地址配置)

        Properties prop = new Properties();
        prop.load(new FileInputStream("First/src/druid.properties"));

 

   4、 获取数据库连接池对象

        DataSource dataSource =  DruidDataSourceFactory.createDataSource(prop);

 

   5、 获取数据库连接Connection

        Connection connection = dataSource.getConnection();

 

   代码示例:
 public static void main(String[] args) throws Exception {
        // 1、 导入jar包

        // 2、 定义配置文件

        // 3、 加载配置文件(根据具体需求)
        Properties prop = new Properties();
        prop.load(new FileInputStream("First/src/druid.properties"));
        // 4、 获取连接池对象(通过数据库连接池工场对象获取)
        DataSource dataSource =  DruidDataSourceFactory.createDataSource(prop);

        // 5、 获取数据库连接Connection
        Connection connection = dataSource.getConnection();

        System.out.println(connection);
    }

 

 
 
 
 
posted @ 2022-09-20 00:39  风陵南  阅读(185)  评论(0)    收藏  举报