JDBC--利用反射及JDBC元数据编写通用的查询方法

1、JDBC元数据(ResuleSetMetaData):描述ResultSet的元数据对象,可以从中获取到结果集中的列数和列名等:

--使用ResultSet类的getMetaData()方法获得ResultSetMetaData对象

--常用的方法有getColumnLabel()、getColumnCount()等。

public static <T> T get(Class<T> clazz, String sql, Object ... args){
    T entity = null;
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    
    try{
        //获取数据库连接
        conn = getConnection();
        //获取PreparedStatement对象并设置参数
        ps = conn.prepareStatement(sql);
        for(int i = 0; i < args.length; i++){
            ps.setObject(i + 1, args[i]);
        }
        //执行sql语句
        rs = ps.executeQuery();
        //获取ResultSet元数据
        ResultSetMetaData rsmd = rs.getMetaData();
        Map<String, Object> map = new HashMap<String, Object>();
        if(rs.next()){
            //遍历数据的每列,取得它们列名的别名和对应的值,并存入Map<String, Object>中
            for(int i = 0; i < rsmd.getColumnCount(); i++){
                String columnLabel = rsmd.getColumnLabel(i + 1);
                Object columnValue = rs.getObject(i + 1);
                
                map.put(columnLabel, columnValue);
            }
        }
        
        if(map.size() > 0){
            //创建运行时类对象
            entity = clazz.newInstance();
            
            //遍历Map<String, Object>的entry集
            for(Map.Entry<String, Object> entry : map.entrySet()){
                String fieldName = entry.getKey();
                Object fieldValue = entry.getValue();
                
                //获取对应名称的类的属性
                Field field = clazz.getDeclaredField(fieldName);
                //属性一般为private的,因此需要将其设为可见
                field.setAccessible(true);
                //为entity对象的对应属性赋值
                field.set(entity, fieldValue);
            }
            return entity;
        }
    }catch(Exception e){
        e.printStackTrace();
    }finally{
        //关闭数据库资源
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(ps != null){
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    return entity;
}
原文地址:https://www.cnblogs.com/tengtao93/p/4972788.html