每日一题 为了工作 2020 0509 第六十七题

package com.swust.jdbc;

import com.swust.constant.Constants;
import com.swust.sparkconf.ConfigurationManager;

import java.sql.*;
import java.util.LinkedList;
import java.util.List;

/**
 * JDBC 辅助组件类
 * 在正式的项目的代码编写过程中,是完全严格按照大公司的coding标准来的
 * 也就是说,在代码中,是不能出现任何hard code(硬编码)的字符
 * 比如“张三”、“com.mysql.jdbc.Driver”
 * 所有这些东西,都需要通过常量来封装和使用
 *
 * @author 雪瞳
 * @Slogan 时钟尚且前行,人怎能就此止步!
 * @Function
 *
 */
public class JdbcHelper {
    // 第一步:在静态代码块中,直接加载数据库的驱动
    // 加载驱动,不是直接简单的,使用com.mysql.jdbc.Driver就可以了
    // 之所以说,不要硬编码,他的原因就在于这里
    //
    // com.mysql.jdbc.Driver只代表了MySQL数据库的驱动
    // 那么,如果有一天,我们的项目底层的数据库要进行迁移,比如迁移到Oracle
    // 或者是DB2、SQLServer
    // 那么,就必须很费劲的在代码中,找,找到硬编码了com.mysql.jdbc.Driver的地方,然后改成其他数据库的驱动类的类名
    // 所以正规项目,是不允许硬编码的,那样维护成本很高
    //
    // 通常,我们都是用一个常量接口中的某个常量,来代表一个值
    // 然后在这个值改变的时候,只要改变常量接口中的常量对应的值就可以了
    //
    // 项目,要尽量做成可配置的
    // 就是说,我们的这个数据库驱动,更进一步,也不只是放在常量接口中就可以了
    // 最好的方式,是放在外部的配置文件中,跟代码彻底分离
    // 常量接口中,只是包含了这个值对应的key的名字
    static {
        try {
            String driver = ConfigurationManager.getProperty(Constants.JDBC_DRIVER);
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    // 第二步,实现JDBCHelper的单例化
    // 为什么要实现单例化呢?因为它的内部要封装一个简单的内部的数据库连接池
    // 为了保证数据库连接池有且仅有一份,所以就通过单例的方式
    // 保证JDBCHelper只有一个实例,实例中只有一份数据库连接池

    private static JdbcHelper instanceSingleton = null;

    public static JdbcHelper getInstanceSingleton(){
        if (instanceSingleton == null){
            synchronized (JdbcHelper.class){
                if (instanceSingleton == null){
                    instanceSingleton = new JdbcHelper();
                }
            }
        }
        return instanceSingleton;
    }
    //数据库连接池

    private LinkedList<Connection> dataSource = new LinkedList<>();

    /**
     * 第三步:实现单例的过程中,创建唯一的数据库连接池
     * 私有化构造方法
     * JDBCHelper在整个程序运行声明周期中,只会创建一次实例
     * 在这一次创建实例的过程中,就会调用JDBCHelper()构造方法
     * 此时,就可以在构造方法中,去创建自己唯一的一个数据库连接池
     */
    private JdbcHelper(){

        //获取数据库连接池的大小,就是说,数据库连接池中要放多少个数据库连接
        int dataSourceSize = ConfigurationManager.getInteger(Constants.JDBC_DATASOURCE_SIZE);
        //创建指定数量的数据库连接,并放入数据库连接池中
        for (int i=0 ; i < dataSourceSize;i++){
            Boolean local = ConfigurationManager.getBoolean(Constants.SPARK_LOCAL);
            String url = null;
            String user = null;
            String password = null;

            if (local){
                url = ConfigurationManager.getProperty(Constants.JDBC_URL);
                user = ConfigurationManager.getProperty(Constants.JDBC_USER);
                password = ConfigurationManager.getProperty(Constants.JDBC_PASSWORD);
            }else {
                url = ConfigurationManager.getProperty(Constants.JDBC_URL_PROD);
                user = ConfigurationManager.getProperty(Constants.JDBC_USER_PROD);
                password = ConfigurationManager.getProperty(Constants.JDBC_PASSWORD_PROD);
            }

            try {
                Connection conn = DriverManager.getConnection(url,user,password);
                dataSource.push(conn);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 第四步,提供获取数据库连接的方法
     * 有可能,你去获取的时候,这个时候,连接都被用光了,你暂时获取不到数据库连接
     * 所以我们要自己编码实现一个简单的等待机制,去等待获取到数据库连接
     * @return
     */
    public synchronized Connection getConnection(){
        while (dataSource.size() == 0){
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //返回连接池内的第一个连接
        return dataSource.poll();
    }

    /**
     * 第五步:开发增删改查的方法
     * 1、执行增删改SQL语句的方法
     * 2、执行查询SQL语句的方法
     * 3、批量执行SQL语句的方法
     * @param sql
     * @param params
     * @return
     */
    public int executeUpdate(String sql,Object[] params){
        int roll = 0;
        Connection conn = null;
        PreparedStatement preparedStatement = null;

        try {
            conn = getConnection();
            //取消事物的自动提交
            conn.setAutoCommit(false);
            preparedStatement = conn.prepareStatement(sql);
            //追加参数
            if (params != null && params.length > 0 ){
                for (int i=0 ; i< params.length ;i++){
                    preparedStatement.setObject(i+1,params[i]);
                }
            }
            //执行
            roll = preparedStatement.executeUpdate();
            //提交事务
            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            //将连接归还连接池内
            if (conn != null){
                dataSource.push(conn);
            }
        }
        return roll;
    }

    /**
     * 批处理
     * @param sql
     * @param paramList
     * @return
     */
    public int[] executeBatch(String sql, List<Object[]> paramList){
        int roll[] = null;
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            connection = getConnection();
            connection.setAutoCommit(false);
            preparedStatement = connection.prepareStatement(sql);

            if (paramList != null && paramList.size()>0){
                for (Object[] params : paramList){
                    for (int i=0 ; i<params.length ; i++){
                        preparedStatement.setObject(i+1, params[i]);
                    }
                    //批量加入sql参数
                    preparedStatement.addBatch();
                }
            }
            //执行
            roll = preparedStatement.executeBatch();
            //提交事务
            connection.commit();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            if (connection != null){
                dataSource.push(connection);
            }
        }
        return roll;
    }

    /**
     * 静态内部类 查询回调接口
     */
    public interface QueryCallback{
        /**
         * 处理查询结果
         */
        void process(ResultSet resultSet) throws Exception;
    }

    public void executeQuery(String sql,Object[] params,QueryCallback callback){

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            connection = getConnection();
            preparedStatement = connection.prepareStatement(sql);

            if (params!=null && params.length>0){
                for (int i = 0;i<params.length;i++){
                    preparedStatement.setObject(i+1,params[i]);
                }
            }

            //执行
           resultSet = preparedStatement.executeQuery();
           //回调查询结果
            callback.process(resultSet);

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {

            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

            if (connection != null){
                dataSource.push(connection);
            }
        }
    }
}

  

原文地址:https://www.cnblogs.com/walxt/p/12858794.html