今日学习了使用DBUTils实现数据的封装(结果集到java对象的映射),并利用泛型实现增删改查的多态:
实现创建一个BaseDao利用QueryRunner类的update与query函数实现增删改查。
public int upDate(String sql,Object ... args) { try { conn=JDBCTools.getConnection(); return qr.update(conn,sql,args); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ JDBCTools.release(conn, ps, rs); } return -1; }
利用了泛型与可变参数实现增删改的多态,这样只需要传入sql语句与相应的数据就可实现增删改,极大的简化了代码。下面是一个例子。
package Dao; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import utils.JDBCTools; import Date.StudentDate; public class StudentDao extends BaseDao{ public int qrUpdateClassById(String studentclass,String studentid) { String sql="UPDATE studentdate set studentclass=? where studentid=?"; return upDate(sql,studentclass,studentid); } public int qrInsert(String studentid,String studentname,String studentpassword,String studentclass) { String sql="INSERT INTO studentdate(studentid,studentname,studentpassword,studentclass) values(?,?,?,?)"; return upDate(sql,studentid,studentname,studentpassword,studentclass); } public int qrDeleteById(String studentid) { String sql="delete from studentdate where studentid=?"; return upDate(sql,studentid); } }
下面是利用泛型与可变参数实现查。
public <T>T queryForOne(Class<T> type,String sql,Object ... args) { try { conn=JDBCTools.getConnection(); return qr.query(conn,sql,new BeanHandler<T>(type),args); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ JDBCTools.release(conn, ps, rs); } return null; } public <T>List<T> queryForList(Class<T> type,String sql,Object ... args) { try { conn=JDBCTools.getConnection(); return qr.query(conn,sql,new BeanListHandler<T>(type),args); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ JDBCTools.release(conn, ps, rs); } return null; }
public StudentDate qrStudentByPassAndId(String password,String id) { String sql="select * from studentdate where studentpassword=? and studentid=?"; return queryForOne(StudentDate.class,sql,password,id); } public List<StudentDate> qraStudentListByClass(String studentclass) { String sql="select * from studentdate where studentclass=?"; return queryForList(StudentDate.class,sql,studentclass); }