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;
    }
}

你可能感兴趣的:(java,sql,jdbc,数据库)