阿里巴巴数据库连接池Druid的使用

89 阅读1分钟

导入依赖

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>

准备数据库

CREATE TABLE `user` (
  `u_id` varchar(12) NOT NULL,
  `u_name` varchar(100) NOT NULL,
  `u_sex` varchar(5) NOT NULL,
  `u_idcard` varchar(18) NOT NULL,
  `u_times` int NOT NULL,
  `u_pwd` varchar(15) NOT NULL,
  `u_state` int NOT NULL,
  `u_role` int NOT NULL,
  PRIMARY KEY (`u_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

编写druid.properties配置文件

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/book?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=GMT%2B8
username=root
password=pwdpwd
// 初始化连接数
initialSize=5
//最大连接池数量
maxActive=10
//获取连接时最大等待时间
maxWait=3000

可以复制,更改对应信息直接使用。

测试

  1. 读取配置文件连接数据库 jdbc.java
package cn.lqy.utils;

import cn.lqy.pojo.User;
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.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

public class jdbc {
    public  User getUser(String ID,String pwd) {
        User user = null;
        try {
            // 加载配置文件
            Properties prop = new Properties();
            prop.load(new FileInputStream("src/main/resources/druid.properties"));
            // 获取连接池对象
            DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
            // 数据库连接对象
            Connection conn = dataSource.getConnection();
            System.out.println("conn = "+conn);
            // 编写sql
            String sql="select * from user where u_id='"+ID+"' and u_pwd='"+pwd+"'";
            System.out.println("sql = "+sql);
            // 获取预编译sql
            PreparedStatement prep = conn.prepareStatement(sql);
            // 执行sql,得到结果集
            ResultSet rs = prep.executeQuery();
            while(rs.next()){
                user = new User();
                user.setUid(rs.getString("u_id"));
                user.setPwd(rs.getString("u_pwd"));
                user.setUtimes(rs.getInt("u_times"));
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return user;
    }
}
  1. Test2.java
package cn.lqy.utils;

import cn.lqy.pojo.User;

public class Test2 {
    public static void main(String[] args) {
        String id = "10010";
        String pwd = "111";
        jdbc jd = new jdbc();
        User user=  new User();
        if(user != null){
            System.out.println(jd.getUser(id,pwd));
        }
    }
}

结果

连接池.png