本人初学者,今天碰见一个封装数据库连接的Dao类方法,看不懂,求大神详细解释一下。

public void openCon() throws SQLException, ClassNotFoundException {

    Class.forName("com.mysql.jdbc.Driver");
    con = DriverManager.getConnection("jdbc:mysql://localhost:3306/li", "root", "root");

}

public List query(String sql,Classc) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException{
openCon();
sta =con.createStatement();
rs=sta.executeQuery(sql);
List list =new ArrayList();
while(rs.next()){
T o =c.newInstance();
Field[] f =c.getDeclaredFields();
for (int i = 0; i < f.length; i++) {
String methodName ="set"+f[i].getName().substring(0,1).toUpperCase()+f[i].getName().substring(1);
Method m =c.getMethod(methodName, String.class);
m.invoke(o, rs.getString(f[i].getName()));
}
list.add(o);
}

    close();
    return list;
}

openCon();
sta =con.createStatement();
这里应该是直接使用了JDBC的方式获得和数据库的连接
接着下面就是通过反射将数据库查出的数据设置到对应的字段中去
while(rs.next()){
T o =c.newInstance();
Field[] f =c.getDeclaredFields();
for (int i = 0; i < f.length; i++) {
String methodName ="set"+f[i].getName().substring(0,1).toUpperCase()+f[i].getName().substring(1);
Method m =c.getMethod(methodName, String.class);
m.invoke(o, rs.getString(f[i].getName()));
}

openCon()这个方法是用来获取数据库连接的,query(String sql,Class c) 而这个方法是传入sql语句以及要查的对象(应该说是类),这里用到了反射机制。可以理解成将你sql查询出来的结果集变成你要的那个对象,然后对这个对象的属性进行操作。