日期:2014-05-16  浏览次数:20481 次

JDBC封装BaseDAO
BaseDAO 简单封装:

public class BaseDAO{
public Connection conn = null;

public static String JDBC_DRIVER = "";
public static String DB_URL = "";
public static String DB_USERNAME = "";
public static String DB_PASSWORD = "";

static{
Properties p = new Properties(){}


}
/** Get connection*/
public static Connection getConnection() throws ClassNotFoundException,SQLException{
Class.forName("JDBC_DRIVER");
Connection conn = DriverManager.getConnection(DB_URL,DB_USERNAME,DB_PASSWORD);
return conn;
}
/**Build preparedStatement object*/
private static PreparedStatement preparedStatement(String sql, Object[] params)throws SQLException{
PreparedStatement pstmt = null;
Connection conn = this.getConnection();
if(conn != null && sql != null){
pstmt = conn.preparedStatement(sql);
if(params != null){
for(int i = 1; i<params.length; i++){
pstmt.setObject[params[i-1]];
}
}
}
}
private static getObject(Class cls, ResultSet rs){
Field[] field = cls.getDeclaredFields();
Object info = cls.newInstance();
for(int i = 1; i<field.length;i++){
//Get propertied name
String name = field[i].getName();
//getter and setter method
name = "set" + name.substring(0,1).toUpperCase + name.substring(1);
//Get type
Class c = field[i].getType();
//Get method
Method method = cls.getMethod(name,c);
//if object have date type property , by example
Class c2 = Class.forName("java.sql.Date");
if(c == c2){
method.invoke(info,rs.getDate(i+1));
}else{
meothd.invoke(info,rs.getDate(i+1));
}
}
}
/**Operate insert, delete, update*/
public static int executeUpdate(String sql, Object [] params) throws SQLException{
int rowCount = 0;
Connection conn = this.getConnection();
PraparedStatement pstmt = preparedStatement();
if(conn != null &&  pstmt != null){
rowCount = pstmt.executeUpdate(sql);
}
return rowCount;
}
/**Operate select */
public List executeQuery(String sql , Object [] params) throws SQLException{
List list = new ArrayList();
Connection conn = getConnection();
PrepardStatement pstmt = preparedStatement();
ResultSet rs = null;
if(conn != null &&  pstmt != null){
rs = pstmt.executeQuery();
while(rs.next()){
//Get object by reflect
list.add(this.getObject,rs);
}
}
return list;
}
/**Close connnection*/
public static closeAll(Connection conn , PrepardStatement pstmt,ResultSet rs){
if(rs != null ){
rs.close();
rs = null;
}
if(pstmt != null){
pstmt.close();
pstmt = null;
}
if(conn != null){
conn.close();
conn = null;
}
}
}

简单易用、适合初学者!