562数据库连接池_druid_基本使用 and563 数据库连接池_druid_工具类

数据库连接池_druid_基本使用

Druid :数据库连接池实现技术,由阿里巴巴捉供的步骤︰
  1.导入jar包 druid-1.0.9.jar

  2.定义配访i文件:
    足properties形式的
    可以叫任意名称,可以放在任意目录下
  3.获取数据库连接池对象∶通过工厂来来获取DruidDataSourceFactory.

  4.获取连接∶getconnection

/**
 * Druid示例
 */
public class Druid_demo01 {
    public static void main(String[] args) throws Exception {
        /**
         步骤:
            1.导入jar包
            2.定义配置文件
            3.加载配置文件
            4.获取连接池对象
            5.获取连接
        */

        /* 加载配置文件 */
        Properties pro = new Properties();
        /* 通过类名称获取字节码文件,就可以获取它的资源路径 */
        InputStream is = Druid_demo01.class.getClassLoader().getResourceAsStream("druid.properties");
        pro.load(is);
        /* 获取连接池对象 */
        DataSource ds = DruidDataSourceFactory.createDataSource(pro);
        /* 获取连接 */
        Connection conn = ds.getConnection();
        /* 执行打印 */
        System.out.println(conn);

    }
}

数据库连接池_druid_工具类

 定义一个工具类

 定义一个类DBCUtils

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

 提供方法

    1.获取连接方法∶通过数据库连接池获取连

    2.释放资源

    3.获取连接池的方法

/**
 * Druid连接池工具类
 */
public class JDBC_utils {
    /* 定义成员变量 */
    private static DataSource ds;

    /* 初始化赋值 */
    static {
        /* 加载配置文件 */
        Properties pro = new Properties();
        try {
            /* 通过漏的方法加载   以及链式编程 */
            pro.load(JDBC_utils.class.getClassLoader().getResourceAsStream("druid.properties"));
            /* 获取DataSource */
            try {
                ds = DruidDataSourceFactory.createDataSource(pro);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /* 获取连接 */
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }
    /* 释放资源 */
    public static void close(ResultSet rs , Statement stmt , Connection conn) {
        if (rs !=null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stmt !=null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn !=null) {
            try {
                /* 归还连接 */
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    /* 获取连接池的方法 */
    public static DataSource getDataSource() {
    return ds;
    }
}

 

 

posted @ 2022-10-19 09:14  ja不会va  阅读(47)  评论(0)    收藏  举报