本教程仅限于 druidv1.2.4 + mysql8.0 + jdk1.8

一、在pom.xml中加入druid依赖文件

<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.4</version>
</dependency>

二、书写配置文件

1. druid数据库连接池技术对配置文件的命名没有要求,因为它需要我们自己拿到配置文件的IO流,然后将IO流作为参数传递,创建数据库连接池对象

2. 我就以 druid.properties 配置文件为例,继续讲解

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
username=root
password=123456
#初始化连接数
initialSize=5
#最大连接数
maxActive=10
#超时时间
maxWait=3000

三、书写代码,测试正常的数据库连接对象的获取

为了方便看代码,我不去捕获异常,直接将异常抛出

public class DruidDemo{
    public static void main(String[] args) throws Exception{
        Properties pros = new Properties();
        pros.load(new BufferedReader(new InputStreamReader(DruidDemo.class.getClassLoader().getResourceAsStream("druid.properties"),"UTF-8")));
        DataSource ds = DruidDataSourceFactory.createDataSource(pros);
        Connection conn = ds.getConnection();
        System.out.println(conn);
    }
}

四、进行一些CRUD操作

public class DruidDemo{
    public static void main(String[] args){
        Properties pros = new Properties();
        pros.load(new BufferedReader(new InputStreamReader(DruidDemo.class.getClassLoader().getResourceAsStream("druid.properties"),"UTF-8")));
        DataSource ds = DruidDataSourceFactory.createDataSource(pros);
        Connection conn = ds.getConnection();
        String sql = "select * from user";
        PreparedStatement pstat = conn.prepareStatement(sql);
        ResultSet rs = pstat.executeQuery();
        while(rs.next()){
            System.out.println(rs.getInt("id")+"\t"+rs.getString("name")+"\t"+rs.getInt("age")+"\t"+rs.getString("gender")+"\t");
        }
    }
}

原文作者:絷缘
作者邮箱:zhiyuanworkemail@163.com
原文地址:https://zhiyuandnc.github.io/-gGSoZP8v/
版权声明:本文为博主原创文章,转载请注明原文链接作者信息