jdbc-连接池

Java 中常用的连接池有 C3P0、DBCP、Druid 等。我们使用Druid,好处:

  • 它的帮助文档是中文,便于查看
  • 它是经过阿里大量数据的使用后的产品,一定会好用

1,添加依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.8</version>
</dependency>

2,修改连接数据库工具类

@Slf4j
public final class JdbcUtil {
    // 定义连接数据库的几个参数
    private static final String DRIVER;
    private static final String URL;
    private static final String USERNAME;
    private static final String PASSWORD;

    private JdbcUtil() {
    }

    // 加载驱动类,这个加载操作只在项目中执行一次即可,无须返回加载
    static {
        try {
            // 读取db.properties配置文件
            InputStream is = JdbcUtil.class.getClassLoader().getResourceAsStream("db.properties");
            Properties prop = new Properties();
            prop.load(is);
            DRIVER = prop.getProperty("jdbc.driver");
            URL = prop.getProperty("jdbc.url");
            USERNAME = prop.getProperty("jdbc.username");
            PASSWORD = prop.getProperty("jdbc.password");
        } catch (IOException e) {
            log.info("加载配置文件出错,错误信息为:" + e.getMessage());
            throw new RuntimeException("加载配置文件出错,错误信息为:" + e.getMessage());
        }
    }


    /**
     * 获取连接对象
     * @return 返回连接对象
     */
    public static DataSource getDataSource() {
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(DRIVER);
        ds.setUrl(URL);
        ds.setUsername(USERNAME);
        ds.setPassword(PASSWORD);
        return ds;
    }

    public static Connection getConnection() {
        try {
            return getDataSource().getConnection();
        } catch (SQLException e) {
            throw new RuntimeException("创建连接对象时出错,错误信息为:" + e.getMessage());
        }
    }

    /**
     * 封装的通用增删改方法
     * @param sql 需要操作的SQL语句
     * @param params 执行SQL语句时需要的参数
     */
    public static int update(String sql, Object... params) {
        Connection conn = null;
        PreparedStatement pstm = null;
        try {
            // 2. 创建连接对象
            conn = getConnection();
            // 3. 创建执行SQL语句对象
            pstm = conn.prepareStatement(sql);
            // 4. 设置参数
            for (int i = 0; i < params.length; i++) {
                pstm.setObject(i + 1, params[i]);
            }
            // 5. 执行SQL语句
            return pstm.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        } finally {
            // 6. 释放资源
            destroy(conn, pstm, null);
        }
    }

    /**
     * 查询多条数据的封装方法
     * @param clazz 结果的封装对象
     * @param sql 要执行的SQL语句
     * @param params 执行SQL语句时需要的参数
     * @param <T> 消费金融泛型类型
     * @return 返回查询的结果集
     */
    public static <T> List<T> query(Class<T> clazz, String sql, Object...params) {
        Connection conn = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        List<T> entities = null;

        try {
            conn = getConnection();
            pstm = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                pstm.setObject(i + 1, params[i]);
            }
            rs = pstm.executeQuery();
            entities = new ArrayList<>();
            // 获取 ResultSet 对象来获取元数据信息
            ResultSetMetaData metaData = rs.getMetaData();
            // 获取SQL语名中字段的个数
            int columnCount = metaData.getColumnCount();
            // 处理结果集
            while (rs.next()) {
                // 通过反射来实例化对象
                //T entity = clazz.newInstance();
                T entity = clazz.getDeclaredConstructor().newInstance();

                for (int i = 1; i <= columnCount; i++) {
                    // getColumnName() 是获取表中的字段名称 SELECT id,name,age FROM xxx
                    //metaData.getColumnName();
                    // getColumnLabel() 是获取SQL中的字段名称 SELECT id,name as n,age FROM xxx
                    // 获取字段的名称
                    String columnLabel = metaData.getColumnLabel(i);
                    // 通过反射获取对象的字段
                    Field field = clazz.getDeclaredField(columnLabel);
                    // 给这个字段设置值
                    field.setAccessible(true);
                    field.set(entity, rs.getObject(columnLabel));
                }
                entities.add(entity);
            }
            return entities;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("查询多条数据时出错,错误信息为:" + e.getMessage());
        } finally {
            destroy(conn, pstm, rs);
        }
    }

    /**
     * 查询多条数据的封装方法
     * @param clazz 结果的封装对象
     * @param sql 要执行的SQL语句
     * @param params 执行SQL语句时需要的参数
     * @param <T> 消费金融泛型类型
     * @return 返回查询的结果
     */
    public static <T> T queryForObject(Class<T> clazz, String sql, Object...params) {
        Connection conn = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        T entity = null;

        try {
            conn = getConnection();
            pstm = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                pstm.setObject(i + 1, params[i]);
            }
            rs = pstm.executeQuery();
            ResultSetMetaData metaData = rs.getMetaData();
            while (rs.next()) {
                if (clazz == Integer.class) {
                    Constructor<T> constructor = clazz.getDeclaredConstructor(int.class);
                    entity = constructor.newInstance(rs.getInt(1));
                } else if (clazz == Long.class) {
                    Constructor<T> constructor = clazz.getDeclaredConstructor(long.class);
                    entity = constructor.newInstance(rs.getLong(1));
                } else {
                    throw new RuntimeException("参数中能传 int 类型或 long 类型。");
                }
            }

            return entity;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("统计查询时出错,错误信息为:" + e.getMessage());
        } finally {
            destroy(conn, pstm, rs);
        }
    }

    /**
     * 通用的释放资源的方法
     * @param conn 连接对象
     * @param pstm 执行语句对象
     * @param rs 结果集对象
     */
    public static void destroy(Connection conn, PreparedStatement pstm, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                log.info("释放 ResultSet 对象时出错,错误信息为:" + e.getMessage());
            }
        }
        if (pstm != null) {
            try {
                pstm.close();
            } catch (SQLException e) {
                log.info("释放 PreparedStatement 对象时出错,错误信息为:" + e.getMessage());
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                log.info("释放 Connection 对象时出错,错误信息为:" + e.getMessage());
            }
        }
    }

}

在这个类中,我们增加了 getDataSource() 方法用于创建连接池对象。然后在 geConection() 方法中从连接池中获取连接对象。而静态代码块中的 加载驱动器类的代码就不再需要,因为这部分的功能已经放到的连接池对象中了。

3,ThreadLocal

JDK1.2 的版本中已经提供了 ThreadLocal对象了,它是为了解决多线程程序并发问题而产生。
这个类提供了以下几个静态方法:

  • get() :用于获取ThreadLocal 中当前线程共享变量的值。
  • set():设置ThreadLocal中当前线程共享的变量的值。
  • remove():移除 ThreadLocal中当前线程共享的变量的值。
  • initialValue:ThreadLocal没有被当前线程赋值时调用当前线程的remove方法后再调用 get 方法时就会返回这个值。
    修改 JdbcUtil 这个工具类,让它支持 ThreadLocal
@Slf4j
public final class JdbcUtil {
    // 数据源连接池对象
    private static DataSource dataSource;
    // ThreadLocal 对象
    private static ThreadLocal<Connection> threadLocal;

    private JdbcUtil() {
    }

    // 加载驱动类,这个加载操作只在项目中执行一次即可,无须返回加载
    static {
        try {
            // 读取db.properties配置文件
            InputStream is = JdbcUtil.class.getClassLoader().getResourceAsStream("db.properties");
            Properties prop = new Properties();
            prop.load(is);

            // 使用Druid连接池工厂方式
            dataSource = DruidDataSourceFactory.createDataSource(prop);
            threadLocal = new ThreadLocal<>();
        } catch (Exception e) {
            log.info("加载配置文件出错,错误信息为:" + e.getMessage());
            throw new RuntimeException("加载配置文件出错,错误信息为:" + e.getMessage());
        }
    }

    /**
     * 获取连接对象
     * @return 返回连接对象
     */
    public static Connection getConnection() {
        // 从当前线程中获取连接
        Connection conn = threadLocal.get();
        if (conn == null) {
            try {
                // 如果没有就从连接池中去获取
                conn = dataSource.getConnection();
                // 放到ThreadLocal中
                threadLocal.set(conn);
            } catch (SQLException e) {
                throw new RuntimeException("创建连接对象时出错,错误信息为:" + e.getMessage());
            }
        }
        return conn;
    }

    /**
     * 封装的通用增删改方法
     * @param sql 需要操作的SQL语句
     * @param params 执行SQL语句时需要的参数
     */
    public static int update(String sql, Object... params) {
        Connection conn = null;
        PreparedStatement pstm = null;
        try {
            // 2. 创建连接对象
            conn = getConnection();
            // 3. 创建执行SQL语句对象
            pstm = conn.prepareStatement(sql);
            // 4. 设置参数
            for (int i = 0; i < params.length; i++) {
                pstm.setObject(i + 1, params[i]);
            }
            // 5. 执行SQL语句
            return pstm.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        } finally {
            // 6. 释放资源
            destroy(conn, pstm, null);
        }
    }

    /**
     * 查询多条数据的封装方法
     * @param clazz 结果的封装对象
     * @param sql 要执行的SQL语句
     * @param params 执行SQL语句时需要的参数
     * @param <T> 消费金融泛型类型
     * @return 返回查询的结果集
     */
    public static <T> List<T> query(Class<T> clazz, String sql, Object...params) {
        Connection conn = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        List<T> entities = null;

        try {
            conn = getConnection();
            pstm = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                pstm.setObject(i + 1, params[i]);
            }
            rs = pstm.executeQuery();
            entities = new ArrayList<>();
            // 获取 ResultSet 对象来获取元数据信息
            ResultSetMetaData metaData = rs.getMetaData();
            // 获取SQL语名中字段的个数
            int columnCount = metaData.getColumnCount();
            // 处理结果集
            while (rs.next()) {
                // 通过反射来实例化对象
                //T entity = clazz.newInstance();
                T entity = clazz.getDeclaredConstructor().newInstance();

                for (int i = 1; i <= columnCount; i++) {
                    // getColumnName() 是获取表中的字段名称 SELECT id,name,age FROM xxx
                    //metaData.getColumnName();
                    // getColumnLabel() 是获取SQL中的字段名称 SELECT id,name as n,age FROM xxx
                    // 获取字段的名称
                    String columnLabel = metaData.getColumnLabel(i);
                    // 通过反射获取对象的字段
                    Field field = clazz.getDeclaredField(columnLabel);
                    // 给这个字段设置值
                    field.setAccessible(true);
                    field.set(entity, rs.getObject(columnLabel));
                }
                entities.add(entity);
            }
            return entities;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("查询多条数据时出错,错误信息为:" + e.getMessage());
        } finally {
            destroy(conn, pstm, rs);
        }
    }

    /**
     * 查询多条数据的封装方法
     * @param clazz 结果的封装对象
     * @param sql 要执行的SQL语句
     * @param params 执行SQL语句时需要的参数
     * @param <T> 消费金融泛型类型
     * @return 返回查询的结果
     */
    public static <T> T queryForObject(Class<T> clazz, String sql, Object...params) {
        Connection conn = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        T entity = null;

        try {
            conn = getConnection();
            pstm = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                pstm.setObject(i + 1, params[i]);
            }
            rs = pstm.executeQuery();
            ResultSetMetaData metaData = rs.getMetaData();
            while (rs.next()) {
                if (clazz == Integer.class) {
                    Constructor<T> constructor = clazz.getDeclaredConstructor(int.class);
                    entity = constructor.newInstance(rs.getInt(1));
                } else if (clazz == Long.class) {
                    Constructor<T> constructor = clazz.getDeclaredConstructor(long.class);
                    entity = constructor.newInstance(rs.getLong(1));
                } else {
                    throw new RuntimeException("参数中能传 int 类型或 long 类型。");
                }
            }

            return entity;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("统计查询时出错,错误信息为:" + e.getMessage());
        } finally {
            destroy(conn, pstm, rs);
        }
    }

    /**
     * 通用的释放资源的方法
     * @param conn 连接对象
     * @param pstm 执行语句对象
     * @param rs 结果集对象
     */
    public static void destroy(Connection conn, PreparedStatement pstm, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                log.info("释放 ResultSet 对象时出错,错误信息为:" + e.getMessage());
            }
        }
        if (pstm != null) {
            try {
                pstm.close();
            } catch (SQLException e) {
                log.info("释放 PreparedStatement 对象时出错,错误信息为:" + e.getMessage());
            }
        }
        if (conn != null) {
            try {
                conn.close();
                // 从 ThreadLocal中删除当前连接对象
                threadLocal.remove();
           } catch (SQLException e) {
                log.info("释放 Connection 对象时出错,错误信息为:" + e.getMessage());
            }
        }
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值