packagecom.GeneralPaging.util;importjava.awt.print.Pageable;importjava.lang.reflect.Field;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.util.ArrayList;importjava.util.List;importcom.GeneralPaging.entity.Book;importcom.mysql.jdbc.Connection;/*** T代表你要对哪个实体类对应表进行查询
*@authorAdministrator
*
*@param*/
public class BaseDao{/***
*@paramsql 查询不同的实体类,对应的sql不同,需要传递
*@paramclz 生产出不同的实体类对应的实例,然后装进list容器中返回
*@parampageable 决定是否分页
*@return*@throwsSQLException
*@throwsIllegalAccessException
*@throwsInstantiationException*/
public List executeQuery(String sql, Class clz,PageBean pageBean)throwsSQLException, InstantiationException, IllegalAccessException{//建立连接
Connection con=(Connection) DBAccess.getConnection();
PreparedStatement pst=null;
ResultSet rs=null;if (pageBean!=null &&pageBean.isPagination()) {//需要分页//算符合条件的总记录数
String countSql=getCountSql(sql);
pst=con.prepareStatement(countSql);
rs=pst.executeQuery();if(rs.next()) {
pageBean.setTotal(rs.getLong(1)+"");
}//查询出符合条件的结果集
String pagSql=getPageSql(sql,pageBean);
pst=con.prepareStatement(pagSql);
rs=pst.executeQuery();
}else{
pst=con.prepareStatement(sql);
rs=pst.executeQuery();
}
List list=new ArrayList<>();
T t;while(rs.next()) {/** 1.实例化一个book对象
* 2.取book的所有属性,然后给其赋值
* 2.1获取所有属性对象
* 2.2给属性对象赋值
* 3.赋完值的book对象装进list容器中*/
//list.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price")));
t=(T) clz.newInstance();
Field[] fields=clz.getDeclaredFields();for(Field field : fields) {
field.setAccessible(true);
field.set(t, rs.getObject(field.getName()));
}
list.add(t);
}//关流
DBAccess.close(con, pst, rs);returnlist;
}/*** 利用原生sql拼接出符合条件的结果集的sql
*@paramsql
*@parampageBean
*@return
*/
privateString getPageSql(String sql, PageBean pageBean) {//TODO Auto-generated method stub
return sql+" LIMIT "+pageBean.getStartIndex()+","+pageBean.getRows();
}/*** 获取符合条件的总记录数的sql
*@paramsql
*@return
*/
privateString getCountSql(String sql) {//TODO Auto-generated method stub
return "SELECT COUNT(1) FROM("+sql+")t;";
}
}