zoukankan      html  css  js  c++  java
  • java_jdbc_反射技术将查询结果封装为对象

    package cn.itcast.Reflect;
    
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import cn.itcast.JdbcUtils;
    
    //反射获取数据库内容
    public class ORMTest {
    
    	public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, SQLException, InstantiationException {
    
    		User2 user = (User2)getObject("select id as Id,username as Username,password as Password from t_user where id=1",User2.class);
    		System.out.println(user.getUsername());
    	}
    	
    	public static Object getObject(String sql,Class clazz) throws SQLException,
    			IllegalAccessException, IllegalArgumentException,
    			InvocationTargetException, InstantiationException {
    		Connection conn = null;
    		PreparedStatement ps = null;
    		ResultSet rs = null;
    		try {
    			conn = JdbcUtils.getConnection();
    			ps = conn.prepareStatement(sql);
    			rs = ps.executeQuery();
    
    			java.sql.ResultSetMetaData rsmd = rs.getMetaData();
    
    			int count = rsmd.getColumnCount();
    			String[] colNames = new String[count];
    
    			for (int i = 1; i <= count; i++) {
    				colNames[i - 1] = rsmd.getColumnLabel(i);
    
    			}
    
    			Object obj = null;
    			Method[] ms = clazz.getMethods();
    			if (rs.next()) {
    				obj = clazz.newInstance();
    				for (int i = 0; i < colNames.length; i++) {
    					String colName = colNames[i];
    					String methodName = "set" + colName;
    					
    					for (Method m : ms) {
    						if (methodName.equals(m.getName())) {
    							m.invoke(obj, rs.getObject(colName));
    						}
    					}
    
    				}
    			}
    			return obj;
    		} finally {
    			JdbcUtils.free(rs, ps, conn);
    		}
    	}
    }
    


     

  • 相关阅读:
    Linux入门第三天——more,less,head,tail,ls 用户权限
    linux 入门第一天
    python入门第八天 摘自--廖雪峰python课程
    python入门第七天
    匿名函数
    返回函数
    高阶函数之filter 和 sorted
    map,reduce高阶函数
    高阶函数 巩固
    装饰器
  • 原文地址:https://www.cnblogs.com/MarchThree/p/3720418.html
Copyright © 2011-2022 走看看