JDBC工具类Java反射封装(自用)


public class JDBCUtils {
    private static String driver;
    private static String url;
    private static String user;
    private static String password;
    private static DruidDataSource druidDataSource;

    /**
     * 初始化 druid数据库连接池
     */
    static {
        InputStream inputStream = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties pro = new Properties();
        try {
            pro.load(inputStream);
            driver = pro.getProperty("driverClassName");
            url = pro.getProperty("url");
            user = pro.getProperty("user");
            password = pro.getProperty("password");

            Class.forName(driver);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(driver);
        druidDataSource.setPassword(password);
        druidDataSource.setUsername(user);
        druidDataSource.setUrl(url);
    }
    //获取连接
    public static Connection getConnection() throws SQLException, ClassNotFoundException {
//        return DriverManager.getConnection(url,user,password);
        return druidDataSource.getConnection();
    }
    //关闭
    public static void close(Connection con, Statement pstmt, ResultSet rs) {

        try {
            if (rs != null) {
                rs.close();
                rs = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (pstmt != null) {
                    pstmt.close();
                    pstmt = null;
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            } finally {
                try {
                    if (con != null) {
                        con.close();
                        con = null;
                    }
                } catch (Exception e3) {
                    e3.printStackTrace();
                }
            }
        }
    }

    // 赋值sql参数
    public static PreparedStatement prepareSql(String sql, Object[] params, Connection con) throws SQLException, ClassNotFoundException {
        PreparedStatement pstmt = con.prepareStatement(sql);
        if (params != null)
            for (int i = 0; i < params.length; i++)
                pstmt.setObject(i + 1, params[i]);
        return pstmt;
    }

    //获取查询结果集字段名称
    private static String[] getColNames(ResultSet rs) throws SQLException {
        ResultSetMetaData rsmd = (ResultSetMetaData) rs.getMetaData();// 整表属性结果集
        // 获取查询的列数
        int count = rsmd.getColumnCount();
        String[] colNames = new String[count];
        for (int i = 1; i <= count; i++) {
            // 获取查询类的别名
            colNames[i - 1] = rsmd.getColumnLabel(i);
        }
        return colNames;
    }

    //查询单条记录
    public static <T> T queryObjectSql(String sql, Object[] params, Class<T> tClass, Connection con) throws Exception {
        PreparedStatement pstmt = null;
        Object object = null;
        ResultSet rs = null;

        try {
            pstmt = prepareSql(sql, params, con);
            rs = pstmt.executeQuery();

            String[] colNames = getColNames(rs);

            while (rs.next()) {
                object = tClass.newInstance();

                for (int i = 0; i < colNames.length; i++) {
                    String colName = colNames[i];// 首字母转换成大写 ==> id setId
                    String methodName = "set" + Character.toUpperCase(colName.charAt(0)) + colName.substring(1);
                    //获取字段对应的值
                    Object value = rs.getObject(colName);
                    // 根据方法名获取Method对象
                    Method method = tClass.getMethod(methodName, value.getClass());
                    if (method != null) {
                        method.invoke(object, value);
                    }
                }
            }

        } catch (SQLException e) {
            throw e;
        } catch (Exception e) {
            throw e;
        } finally {
            close(null, pstmt, rs);
        }
        return (T) object;
    }

    //查询多条记录
    public static <T> List<T> queryListSql(String sql, Object[] params, Class<T> clazz, Connection con) throws Exception {
        PreparedStatement pstmt = null;
        Object object = null;
        List<T> list = null;
        ResultSet rs = null;
        try {
            pstmt = prepareSql(sql, params, con);
            rs = pstmt.executeQuery();

            String[] colNames = getColNames(rs);

            list = new ArrayList<T>();

            while (rs.next()) {
                object = clazz.newInstance();

                for (int i = 0; i < colNames.length; i++) {
                    String colName = colNames[i];// 首字母转换成大写 数据库列名与set不同 id setId
                    String methodName = "set" + Character.toUpperCase(colName.charAt(0)) + colName.substring(1);

                    // 直接根据方法名获取对应的Method对象
                    Object value = rs.getObject(colName);
                    Method m = clazz.getMethod(methodName, value.getClass());
                    if (m != null) {
                        m.invoke(object, value);
                    }
                }

                list.add((T) object);

            }
        } catch (SQLException e) {
            throw e;
        } catch (Exception e) {
            throw e;
        } finally {
            close(con, pstmt, rs);
        }

        return list;
    }

    //增删改
    public static int updateSql(String sql, Object[] params,  Connection con) throws SQLException ,Exception {
        int i = -1;
        PreparedStatement pstmt = null;
        try {
            pstmt = prepareSql(sql, params, con);
            i = pstmt.executeUpdate();
        } catch (SQLException e) {
            throw e;
        } catch (Exception e) {
            throw e;
        } finally {
            close(con, pstmt, null);
        }

        return i;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值