java 万能转换器 输入SQL 直接得到ArrayList

//java万能List转换器
    public  static <T> ArrayList<T> ToList(Class<T> clazz,String sql) throws Exception
    {
        Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
        String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=Appscomm",user="sa",password="123456"; 
        Connection conn= DriverManager.getConnection(url,user,password); 
        Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE); 
        ResultSet rs=stmt.executeQuery(sql); 
         ArrayList<T> list=new ArrayList<T> ();
        try {  
            ResultSetMetaData metaData=rs.getMetaData();
            T obj = clazz.newInstance();//创建一个对象
            Field[] propertys=  obj.getClass().getDeclaredFields();  //获取 所有属性
            
            ArrayList<String> Columns=new  ArrayList<String> ();//获取 数据库列
            for(int column=1;column<=metaData.getColumnCount();column++) {    Columns.add(metaData.getColumnName(column));  }
        
             while(rs.next()) {
                obj = clazz.newInstance();
                for(Field p: propertys){
                     String colunmName=p.getName();
                     if(p.isAnnotationPresent(DBColumn.class)) {colunmName=p.getDeclaredAnnotation(DBColumn.class).Name();}//针对数据库字段和 程序属性字段不是一一对应情况
                     if(Columns.contains(colunmName)) {
                          String method="set"+p.getName();
                         Class<?> type = p.getType(); 
                         String typeName=type.getName();
                         String value=rs.getString(colunmName);
                         Method m = obj.getClass().getMethod(method,type);  
                         if(value=="" ||value==null || value.equalsIgnoreCase("null")) {
                             value="0";
                         }
                         if(typeName.equals("float")) {
                              m.invoke(obj,Float.parseFloat(value));  continue;
                         }
                         if(typeName.equals("java.lang.String")) {
                              m.invoke(obj,value);    continue;
                         }
                         if(typeName.equals("int")) {
                               m.invoke(obj,Integer.valueOf(value));      continue;
                         }
//....还有其他的数据类型,这里 抛砖引玉,自己添加 } } list.add(obj); } }
catch (Exception e) { e.printStackTrace(); } finally { rs.close(); stmt.close(); conn.close(); } return list; }

注解代码

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
 @interface DBColumn {
     String Name();
}

Model代码

class Record
{
    int StudentNo;
     @DBColumn(Name="StudentName1")
    String StudentName;//数据库是StudentName1,用注解替代
    float Chinese;
    float Math;
    float English;
    float TotalScore;
   
    public int getStudentNo() {
        return StudentNo;
    }
    
    public void setStudentNo(int studentNo) {
        StudentNo = studentNo;
    }
    public String getStudentName() {
        return StudentName;
    }
    
    public void setStudentName(String studentName) {
        StudentName = studentName;
    }
    public float getChinese() {
        return Chinese;
    }
    public void setChinese(float chinese) {
        Chinese = chinese;
    }
    public float getMath() {
        return Math;
    }
    public void setMath(float math) {
        Math = math;
    }
    public float getEnglish() {
        return English;
    }
    public void setEnglish(float english) {
        English = english;
    }
    public float getTotalScore() {
        return TotalScore;
    }
    public void setTotalScore(float totalScore) {
        TotalScore = totalScore;
    }
}

调用

ArrayList<Record>  RecordList= ToList(Record.class,"select * from Record");
        for(Record r : RecordList) {
            System.out.println("Id = " + r.getStudentNo() + ", UserName = " + r.getStudentName()
            + ", Chinese = " + r.getChinese() + ",  Math = " + r.getMath()
            + ", English = " + r.getEnglish()+ "totalScore = " + r.getTotalScore());
        }
        

 

posted @ 2018-03-23 18:56  正定聚  阅读(485)  评论(0编辑  收藏  举报