Template

今天介绍用Template 减少代码输入

 

abstract public class Template {
	private DBTools db=new DBTools(); 
	
	public  Connection conn ;
	 public PreparedStatement p = null;
	 public  ResultSet rs = null;
	public Template(){
		conn=db.getConnection();

		
	}
	
public Object doInTemp(){
//System.out.println("before");
	Object o = null;
	try {
		o = Execute();
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		
	}
//	System.out.println("after");
	db.closeAll(conn, p, rs);
	
	return o;
	
	
	
}

abstract public Object Execute()throws SQLException;

}

 上面是一个模板类

public class TeacherDao implements TeacherIntf {

	
	
	public Object addOther(final Other o){
		
		return new Template(){
			
			@Override
			public Object Execute() throws SQLException {
				p = conn
				.prepareStatement("insert into others(content, tea_id,o_date) values(?,?,?)");

			p.setString(1, o.getContent());
			p.setInt(2,o.getTeaid());
				p.setString(3,o.getO_date());
				return p.executeUpdate();
			}
			
		}.doInTemp();
		
	}
	。。。。。。。。
}

 

这样省去打开connection和关闭conneciton了

你可能感兴趣的:(template)