手写多数据源连接,封装数据增删,类似于Mybatis

工具类

public class DBConn {
    List<Map<String, Object>> dataInfo = new ArrayList<Map<String, Object>>();
    public Connection connection = null;
    private Statement statement = null;
    private ReadConfig readConfig = new ReadConfig();
    String[] dataBaseArray = getConnBase();

    /**
     * 加载数据库连接
     */
    {
        Conn(dataBaseArray);
    }

    //传入DBName获取数据库连接 多数据源配置方法
    // 传入DBName参数必须跟resources/config.properties中的配置信息开头一致
    public Connection Conn(String[] DBNameArray) {
        for (String DBName : DBNameArray) {
            Map map = new HashMap();
            try {
                Class.forName(app.JDBC_DRIVER);
                connection = DriverManager.getConnection(getConnDetail(DBName, "url"), getConnDetail(DBName, "user"), getConnDetail(DBName, "pass"));
                statement = connection.createStatement();
                System.out.println(DBName+"数据库连接成功!");
            } catch (ClassNotFoundException | SQLException e) {
                System.out.println(DBName+"数据库连接失败!");
                connection = null;
                statement = null;
            } finally {
                map.put(DBName, connection);
                map.put(DBName+"Stmt", statement);
                dataInfo.add(map);
            }
        }
        return connection;
    }

    /**
     * @param DBName
     * @return 返回指定数据源Connection对象
     */
    public Connection getConn(String DBName) {
        for (Map map : dataInfo) {
            if (map.containsKey(DBName)) {
                return (Connection) map.get(DBName);
            }
        }
        return null;
    }

    public Statement getStmt(String DBName) throws SQLException {
        for (Map map : dataInfo) {
            if (map.containsKey(DBName)) {
                return (Statement) map.get(DBName+"Stmt");
            }
        }
        return null;
    }

    public ResultSet getResult(String DBName, String sql) throws SQLException {
        System.out.println("执行SQL --> " + sql);
        return getStmt(DBName).executeQuery(sql);
    }

    /**
     * @param DBName
     * @param sql
     * @return 查询表格内容
     * @throws SQLException
     */
    //获取表格信息
    public List<Map> getTableInfo(String DBName, String sql) throws SQLException {
        ResultSet resultSet = getResult(DBName, sql);
        String[] header = getResultMetaData(DBName, sql,resultSet);
        List list = new ArrayList();
        while (resultSet.next()) {
            Map map = new HashMap();
            for (int i = 1; i < header.length; i++) {
                map.put(header[i], resultSet.getString(header[i]));
            }
            list.add(map);
        }
        resultSet.close();
        System.out.println("resultSet -->" + "  CLOSED!");
        return list;
    }

    /**
     * @param DBName
     * @param sql
     * @param args
     * @return 更新或插入表格信息 传参用String[]
     * @throws Exception
     */
    // insert into tab values (id , column) values ( ? , ? )
    public int updateTableInfo(String DBName, String sql, String[] args) throws Exception {
        String updateSQL = "";
        if (sql.contains("?")) {
            if(!sql.endsWith("?")){
                args = Arrays.copyOf(args,args.length + 1);
                args[args.length - 1] = null;
            }
            String[] parm = sql.split("\\?");
            for (int i = 0; i < parm.length; i++) {
                updateSQL += parm[i] + formatColumn(args[i]);
            }
        }
        System.out.println("执行SQL --> " + updateSQL);
        return getStmt(DBName).executeUpdate(updateSQL);
    }

    /**
     * @param DBName
     * @param sql
     * @param map
     * @return 更新或插入表格数据 传参使用Map
     * @throws Exception
     */
    // insert into tab values (id , column) values ( #{id} , #{column})
    public int updateTableInfo(String DBName, String sql, Map map) throws Exception {
        for(int i = 0 ; i < stringAppearTimes(sql,"#") ; i ++){
            for(Object column : map.keySet()){
                String c = "#{"+column.toString()+"}";
                sql = sql.replace(c,formatColumn(map.get(column).toString()));
            }
        }
        System.out.println("执行SQL --> " + sql);
        return getStmt(DBName).executeUpdate(sql);
    }


    //获取指定sql查询的列名  推荐查询表格内容时使用
    public String[] getResultMetaData(String DBName, String sql,ResultSet resultSet) throws SQLException {
        ResultSetMetaData rsmd = resultSet.getMetaData();
        String[] metaData = new String[rsmd.getColumnCount() + 1];
        for (int i = 1; i < metaData.length; i++) {
            metaData[i] = rsmd.getColumnName(i);
        }
        return metaData;
    }
    //获取指定sql查询的列名  推荐查询表格头部的时候使用
    public String[] getResultMetaData(String DBName, String sql) throws SQLException {
        ResultSetMetaData rsmd = getResult(DBName,sql).getMetaData();
        String[] metaData = new String[rsmd.getColumnCount() + 1];
        for (int i = 1; i < metaData.length; i++) {
            metaData[i] = rsmd.getColumnName(i);
        }
        return metaData;
    }

    //读取配置文件中的数据源配置信息
    public String getConnDetail(String DBName, String column) {
        return readConfig.getPropertiesValue(DBName + "_MYSQL." + column.toUpperCase());
    }

    //读取数据源数组
    public String[] getConnBase() {
        return readConfig.getPropertiesValue("DATABASE").replace("[", "").replace("]", "").split(",");
    }

    //关闭所有已经打开的连接
    public boolean closeConnection() {
        try {
            for (String DBName : dataBaseArray) {
                for (Map map : dataInfo) {
                    if (map.containsKey(DBName)) {
                        ((Statement)map.get(DBName+"Stmt")).close();
                        ((Connection) map.get(DBName)).close();
                        System.out.println("断开"+DBName+"数据库连接");
                    }
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @param Column
     * @return SQL中varchar类型处理
     */
    public String formatColumn(String Column) {
        int c = 0;
        try {
            c = Integer.parseInt(Column);
        } catch (Exception e) {
            if(Column == null){
                return "";
            }
            return "\'" + Column + "\'";
        }
        return c + "";
    }

    /**
     * @param str
     * @param pattern
     * @return str中pattern出现的次数
     */
    public int stringAppearTimes(String str,String pattern){
        int count = 0,index = 0;
        while((index = str.indexOf(pattern,index)) != -1) {
            count++;
            index += 1;
        }
        return count;
    }
}

测试

		DBConn DBConn = new DBConn();
        Connection AH_connection = DBConn.getConn("AH");
        Connection JS_connection = DBConn.getConn("JS");
        System.out.println(AH_connection);
        System.out.println(JS_connection);

        String[] AH_column = DBConn.getResultMetaData("AH","SELECT * FROM result_task");
        String[] JS_column = DBConn.getResultMetaData("JS","SELECT * FROM config_job");
        String[] BSC_column = DBConn.getResultMetaData("BSC","SELECT * FROM config_scriptdetail");

        List list = DBConn.getTableInfo("BSC","SELECT * FROM config_scriptdetail WHERE ID = 1");

        List list2 = DBConn.getTableInfo("BSC","SELECT ID FROM config_scriptdetail WHERE ID = 3");

        for(int i = 0 ; i < list.size() ; i ++){
            System.out.println(list.get(i).toString());
        }
        String[] arg = {"10","2","Success","153"};
        int c = DBConn.updateTableInfo("JS","UPDATE taskinfo SET TaskID = ? , JobID = ? , Status = ? WHERE ID = ?",arg);
        String[] paramters = {"2","ConfigBackup"};

        Map map = new HashMap();
        map.put("ID",5);
        map.put("SiteName","TestSiteName");
        int c2 = DBConn.updateTableInfo("JS","INSERT INTO config_allsite (ID,SiteName) values (#{ID} , #{SiteName})",map);
        int cS = DBConn.updateTableInfo("JS","INSERT INTO boarddatatyperef (BoardID,DataType) values (? , ?)",paramters);
        DBConn.closeConnection();

配置

DATABASE = [AH,JS,BSC]

AH_MYSQL.JDBC_DRIVER = com.mysql.jdbc.Driver
AH_MYSQL.URL = jdbc:mysql://127.0.0.1:3306/develop_ecmp_cnais_jscm
AH_MYSQL.USER = root
AH_MYSQL.PASS = 123456

JS_MYSQL.JDBC_DRIVER = com.mysql.jdbc.Driver
JS_MYSQL.URL = jdbc:mysql://192.168.1.172:3306/ah_abms_test
JS_MYSQL.USER = root
JS_MYSQL.PASS = abc123

BSC_MYSQL.JDBC_DRIVER = com.mysql.jdbc.Driver
BSC_MYSQL.URL = jdbc:mysql://192.168.1.120:3306/bsc
BSC_MYSQL.USER = root
BSC_MYSQL.PASS = abcqwe

读取配置文件类

public class ReadConfig {
    private static Properties prop = null;
    private static File properties = null;
    static {
        properties = new File(ReadConfig.class.getClassLoader().getResource("conn-config.properties").getFile());
        try {
            if (properties.exists()) {
                prop = new Properties();
                InputStream in = new BufferedInputStream(new FileInputStream(properties));
                prop.load(in);
            } else {
                System.out.println("在项目resources下新建config.properties文件!\r\n打包可运行jar时请放在jar包运行同级目录下!");
                throw new FileNotFoundException();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @deprecated 添加或更新一个参数
     * @param key
     * @param value
     * @return true false
     */
    public boolean updatePropertie(String key, String value) {
        try {
            OutputStream fos = new FileOutputStream(properties);
            prop.setProperty(key, value);
            prop.store(fos, "Update value");
            fos.close();
        } catch (IOException e) {
            return false;
        }
        return true;
    }
    /**
     * 获取配置文件中的参数值
     * @param key
     * @return value
     */
    public String getPropertiesValue(String key){
        return prop.getProperty(key.trim()).trim();
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值