JDBCUtils.java 5.63 KB
package com.lhcredit.common.utils;

import org.apache.commons.lang3.reflect.FieldUtils;

import java.lang.reflect.Field;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class JDBCUtils {
    public static Connection connection = null;
    public static PreparedStatement preparedStatement = null;
    public static ResultSet resultSet = null;

    /**
     * 连接数据库
     *
     * @return
     */
    public static Connection getConnection() {
        String url = "jdbc:mysql://opc-2zewlxa1xkof5b31v.rwlb.rds.aliyuncs.com:3306/apidata?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8";
        String user = "tlz";
        String password = "tlzdev-polardb-01";
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection = DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * 关闭资源
     */
    public static void close() {
        try {
            if (connection != null) {
                connection.close();
                connection = null;
            }
            if (preparedStatement != null) {
                preparedStatement.close();
                preparedStatement = null;
            }
            if (resultSet != null) {
                resultSet.close();
                resultSet = null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    /**
     * 将结果集转换成实体对象集合
     *
     * @param res 结果集
     * @param c   实体对象映射类
     * @return
     * @throws SQLException
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    public static List Populate(ResultSet rs, Class cc) throws SQLException, InstantiationException, IllegalAccessException {

        //结果集 中列的名称和类型的信息
        ResultSetMetaData rsm = rs.getMetaData();
        int colNumber = rsm.getColumnCount();
        List list = new ArrayList();
        // Field[] fields = cc.getDeclaredFields();
        //获取当前类 及父类的所有属性
        Field[] fields = FieldUtils.getAllFields(cc);
        //遍历每条记录
        while (rs.next()) {
            //实例化对象
            Object obj = cc.newInstance();
            //取出每一个字段进行赋值
            for (int i = 1; i <= colNumber; i++) {
                Object value = rs.getObject(i);
                //匹配实体类中对应的属性
                for (int j = 0; j < fields.length; j++) {
                    Field f = fields[j];
                    String columnName = rsm.getColumnName(i);


                    String replace = columnName.replace("_", "");
                    if ("bank_type".equals(columnName)) {
                        replace = "cpjglb";
                    }
                    String name = f.getName();
                    if (name.toLowerCase().equals(replace.toLowerCase())) {
                        boolean flag = f.isAccessible();
                        f.setAccessible(true);
                        f.set(obj, value);
                        f.setAccessible(flag);
                        break;
                    }
                }

            }
            list.add(obj);
        }
        return list;
    }

    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
//           String weqeqw_qweqwq = upperTable("weqeqw_qweqwq");
//           System.out.println(weqeqw_qweqwq);
//        Connection conn = JDBCUtils.getConnection();      //JDBCUtils 自己定义的一个类
//        PreparedStatement pre = null;
//        ResultSet res = null;
//        String sql = "select * from user where username=?";
//        try {
//            pre = conn.prepareStatement(sql);
//            pre.setString(1,"wqq");
//            res = pre.executeQuery();
//            //调用将结果集转换成实体对象方法
//            List list = JDBCUtils.Populate(res, User.class);
//            //循环遍历结果
//            for(int i=0;i<list.size();i++){
//                User user = (User) list.get(i);
//                System.out.println("[username = "+ user.getUsername()+",passwd = "+ user.getPassword()+"]");
//            }
//
//        } catch (SQLException e) {
//            e.printStackTrace();
//        }
    }

    public static String upperTable(String str) {
        // 字符串缓冲区
        StringBuffer sbf = new StringBuffer();
        // 如果字符串包含 下划线
        if (str.contains("_")) {
            // 按下划线来切割字符串为数组
            String[] split = str.split("_");
            // 循环数组操作其中的字符串
            for (int i = 0, index = split.length; i < index; i++) {
                // 递归调用本方法
                String upperTable = upperTable(split[i]);
                // 添加到字符串缓冲区
                sbf.append(upperTable);
            }
        } else {// 字符串不包含下划线
            // 转换成字符数组
            char[] ch = str.toCharArray();
            // 判断首字母是否是字母
            if (ch[0] >= 'a' && ch[0] <= 'z') {
                // 利用ASCII码实现大写
                ch[0] = (char) (ch[0] - 32);
            }
            // 添加进字符串缓存区
            sbf.append(ch);
        }
        // 返回
        return sbf.toString();
    }
}