泛型反射数据库通用连接类

package dao;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public abstract class GenericDAO<T>  
{  
    public static final String DRIVER="com.microsoft.sqlserver.jdbc.SQLServerDriver";
 public static final String URL="jdbc:sqlserver://localhost:1433;databasename=restrant";
 public static final String DBNAME="sa";
 public static final String DBPASS="sa1234";
 
 private Connection conn=null;
 private PreparedStatement pstmt=null;
 private ResultSet rs=null;
 
 public void getConn() {
  try {
   Class.forName(DRIVER);
   this.conn=DriverManager.getConnection(URL,DBNAME,DBPASS);
  } catch (ClassNotFoundException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  }catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 
 public void closeAll(){
  if(rs!=null){try{rs.close();}catch(Exception ex){ex.printStackTrace();}}
  if(pstmt!=null){try{pstmt.close();}catch(Exception ex){ex.printStackTrace();}}
  if(conn!=null){try{conn.close();}catch(Exception ex){ex.printStackTrace();}}
 }
 
 public List<T> executeSQL(String sql,String[] params){
  this.getConn();
  try {
   this.pstmt=this.conn.prepareStatement(sql);
   if(params!=null){
    for(int i=1;i<=params.length;i++){
     this.pstmt.setString(i, params[i-1]);
    }
   }
   this.rs=this.pstmt.executeQuery();
   int count=this.rs.getMetaData().getColumnCount();
   List<T> list=new ArrayList<T>();
   Class<T> cls=(Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
   while(rs.next()){
    T t=(T)cls.newInstance();
    Field[] fields=cls.getDeclaredFields();
    for(int i=0;i<fields.length;i++){
     fields[i].setAccessible(true);
     fields[i].set(t, this.rs.getObject(fields[i].getName()));
    }
    list.add(t);
   }
   return list;
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   return null;
  }catch(InstantiationException e){
   // TODO Auto-generated catch block
   e.printStackTrace();
   return null;
  }catch(IllegalAccessException e){
   e.printStackTrace();
   return null;
  }finally{
   this.closeAll();
   rs=null;
   pstmt=null;
   conn=null;
  }
 }
 
 public int executeUpdate(String sql,String[]params){
  int result=-1;
  try{
   this.getConn();
   this.pstmt=this.conn.prepareStatement(sql);
   if(params!=null){
    for(int i=1;i<=params.length;i++)
     this.pstmt.setString(i, params[i-1]);
   }
   result=this.pstmt.executeUpdate();
   return result;
  }catch(Exception ex){
   ex.printStackTrace();
   return -1;
  }finally{
   this.closeAll();
   rs=null;
   pstmt=null;
   conn=null;
  }
  
 }

posted on 2010-11-24 20:38  aurawing  阅读(316)  评论(0编辑  收藏  举报