使用反射 来操作  这里是练习反射的使用数据库工具类

  1. private static final String DRIVER = "com.mysql.jdbc.Driver";  
  2.     private static final String USER = "root";  
  3.     private static final String PW = "1234";  
  4.     private static final String URL="jdbc:mysql://localhost:3306/reflction";  
  5.     /** 
  6.      * 链接数据库 
  7.      * @return 
  8.      */  
  9.     public static Connection getConnection(){  
  10.         try {  
  11.             Class.forName(DRIVER);  
  12.             Connection con = DriverManager.getConnection(URL, USER, PW);  
  13.             System.out.println("Connection OK .....");  
  14.             return con;  
  15.         } catch (Exception e) {  
  16.             System.out.println("Connection error...");  
  17.             e.printStackTrace();  
  18.         }  
  19.         return null;  
  20.     }  

public Object getById(Class clazz, Integer id) throws Exception{
Object obj = clazz.newInstance();//实列一个
//创建链接
Connection con = JdbcUtils.getConnection();
//获取实体的名字 需要拼接 从最后一个点开始
String tablename = clazz.getName().substring(clazz.getName().lastIndexOf("."));
//拼接sql 语句
String sql = "select * from "+tablename+" where id=?";

try {
PreparedStatement psmt = con.prepareStatement(sql);
psmt.setInt(1, id);
//查到结果集
ResultSet rs = psmt.executeQuery();
//遍历结果
while(rs.next()){
//得到所有属性
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {//遍历属性
//获取属性名
String fname = field.getName();
//获取属性类型 int
Class type = field.getType();
//
Method rsGetMethod = ResultSet.class.getMethod("getObject", String.class);
Object value = rsGetMethod.invoke(rs, fname);
//更改修饰符权限
field.setAccessible(true);
field.set(obj, value);
}

交流群: 386451316

原文地址:http://blog.csdn.net/u010982856/article/details/40151021

posted on 2014-12-27 18:43  Striver_zw  阅读(147)  评论(0编辑  收藏  举报