数据库连接池

Java
464
0
0
2022-08-14

##1 Druid 数据库连接池演示示例

–druid-1.0.9.jar

//1. 导入jar 包 druid .jar

//2.定义配置文件

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/test
username=root
password=sj123
# 初始化连接数量
initialSize=5
# 最大连接数
maxActive=10
#最大等待时间
maxWait=3000

//3.加载配置文件

Properties pro = new Properties();
// src 下配置文件
pro.load(DruidDemo.class.getClassLoader().getResourceAsStream("resources/druid.properties"));
DataSource ds = DruidDataSourceFactory.createDataSource(pro);
Connection conn = ds.getConnection();
 Statement state = conn.createStatement();
 ResultSet rs = state.executeQuery("select * from user");
 while (rs.next()){
     String name = rs.getString("name");
     System.out.println(name);
 }
System.out.println(conn);
 conn.close();
 state.close();
 rs.close();

2 定义工具类

1.定义一个类JDBCUtils

2.提供静态代码块加载配置文件,初始化连接池对象

3.提供方法

- 1获取连接方法:通过数据库连接池获取连接

2 释放资源

3. 获取连接池的方法

工具类演示示例

/**
 * Druid 连接池工具类
 */

public class JDBCUtils {
    //1.定义成员变量DataSource 
    private static DataSource ds;
    static {
        //1. 加载配置文件
        Properties pro = new Properties();
        try {
            pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("resources/druid.properties"));
            ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (IOException e) {
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public  static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    public static void  close(Statement state,Connection conn)  {
       close(null,state,conn);
    }
    public  static  void  close(ResultSet rs, Statement state, Connection conn){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(state!=null) {
            try {
                state.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static  DataSource getDataSource(){
        return ds;
    }
}

2 测试调用

public class DruidDemo2 {
    public static void main(String[] args) {
        try {
            Connection conn= JDBCUtils.getConnection();
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("select * from user");
            while (rs.next()){
                System.out.println(rs.getString("name"));
            }
            JDBCUtils.close(rs, stmt,conn );
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}