刚学反射就想练下手,有错希望大家指正,这样才能学到更多。
public class CommonDao {
private String DEFAULT_DRIVER="com.mysql.cj.jdbc.Driver";
private String DEFAULT_USER="?";
private String DEFAULT_PASSWORD="?";
private String DEFAULT_URL="jdbc:mysql://localhost:3306/student?serverTimezone=Asia/Shanghai";
private String SELECT="select columnName from tbName condition";
private String UPDATE="";
private String DELETE="";
private String[] columnName;
private String dataBase;
private Connection con;
private PreparedStatement pre;
private ResultSet res;
{//创建该类实例的时候让其加载驱动并初始化con
try{
Class.forName(DEFAULT_DRIVER);
dataBase="student";
con=getCon();
}catch (Exception e){
e.printStackTrace();
}
}
private Connection getCon() throws SQLException {
return DriverManager.getConnection(DEFAULT_URL, DEFAULT_USER, DEFAULT_PASSWORD);
}
//关闭连接
private void closeAll(PreparedStatement pre,ResultSet res) throws SQLException {
if(res!=null && res.isClosed()) {res.close();res=null;}
if(pre!=null && pre.isClosed()) {pre.close();pre=null;}
}
protected ArrayList<Object> select(Object o,String tbName, String condition) throws SQLException, IllegalAccessException, InstantiationException {
getColumnName(tbName,condition);
if(columnName==null || con==null) throw new NullPointerException("空指针异常!");
ArrayList<Object> list=new ArrayList<>();
res=getAllData(tbName, condition);
Class clazz=o.getClass();
Field[] fields=clazz.getDeclaredFields();
//赋予设置私有成员的权限
AccessibleObject.setAccessible(fields, true);
while(res.next()){
for(int i=0;i<fields.length;i++){
//这里通过比较o对象成员变量的名字来判断是否和数据库列名一致当然不是非常严谨 后期还需要对类型进行判定
for(int j=0;j<columnName.length;j++){
if(fields[i].getName().equals(columnName[j])){
fields[i].set(o, res.getObject(columnName[j]));
}
}
}
list.add(o);
o=clazz.newInstance();//获取一个与o一样的新的实例
}
closeAll(pre, res);
return list;
}
//获取该表的列名
public void getColumnName(String tbName,String condition) throws SQLException {
try{
res=getAllData(tbName, condition);
ResultSetMetaData rem=res.getMetaData();
int len=rem.getColumnCount();
columnName=new String[len];
for(int i=0;i<columnName.length;i++){
columnName[i]=rem.getColumnName(i+1);
}
}catch (Exception e){
e.printStackTrace();
}finally {
closeAll(pre,res);
}
}
private ResultSet getAllData(String tbName,String condition) throws SQLException {
String sql=SELECT;
ResultSet res = null;
if(con==null){
throw new NullPointerException("空指针异常!");
}
try{//这个地方可以用StringBuilder 来做字符串替换效率会更高点
sql=sql.replace("columnName", "*").replace("tbName", tbName).replace("condition", condition);
pre=con.prepareStatement(sql);
res=pre.executeQuery();
}catch (Exception e){
e.printStackTrace();
}
return res;
}
}