DAO模式

什麼是DAO模式:html

DAO(Data Access Object Pattern)用於將低層的數據操做API與上層的業務邏輯層分離,其主要涉及如下幾個部分:java

1.Data Access Object Interfacemysql

定義了在model object上的標準操做接口。sql

2.Data Access Object concrete class數據庫

實現了1中的接口,負責從database或者xml等中操做數據。編程

3.Model Object or Value Object架構

簡單的POJO對象。app

一.  DAO全程是Data Access Object,是J2EE核心模式之一,主要用於上層應用程序與持久化機制之間的中間層,對於底層的數據庫持久化,其各部分關係答題以下:ide

 

一、使用JDBC的API訪問數據庫工具

鏈接、SQL語句執行、結果

java.sql.Driver:各個數據庫廠商須要實現該接口,驅動的標記

java.sql.Connection:封裝和數據庫的鏈接

java.sql.Statement:封裝須要執行的SQL語句

java.sql.ResultSet:封裝查詢的結果集

java.sql.PreparedStatement接口

二、JDBC編程步驟 

step1——加載驅動

step2——獲取鏈接對象

step3——執行SQL語句

step4——處理結果集

step5——關閉資源

3.DAO的架構 

 

 

實現接口:

示例:

public class NewsDAOImpl  implements INewsDAO{
    BaseDao dao = new BaseDao();
    @Override
    public List<News> findAll() throws Exception {
          List<News> list=new ArrayList<News>();
           String sql="select * from news";
          ResultSet rs=dao.executeQuery(sql);
          if (rs!=null) {
          while (rs.next()) {
             News grade=new News();
            grade.setId(rs.getInt(1));
            grade.setName(rs.getString(2));
            grade.setAuthor(rs.getString(3));
            grade.setCreateTime(rs.getDate(4));
            grade.setContent(rs.getString(5));
            list.add(grade);
        }
        }
            return list;
    }

}

工具類:

public class BaseDao {
    private static final String driver="com.mysql.jdbc.Driver";
    private static final String url="jdbc:mysql:///news2230";
    private static final String username="cai";
    private static final String password="root";
    
    private Connection con;
    private PreparedStatement ps;
    private ResultSet rSet;
    
    public Connection getConnection() throws Exception {
        Class.forName(driver);
        if (con==null||con.isClosed()) {
            con=DriverManager.getConnection(url,username,password);
        }
        return con;
    }
    
  
    //增長 修改 刪除
    public int executeUpdate(String sql,Object...objects) throws  Exception {
        getConnection();
        ps=con.prepareStatement(sql);
    for (int i = 0; i < objects.length; i++) {
        ps.setObject(i+1, objects[i]);
    }
        int count=ps.executeUpdate();
        return  count;
        
    }
    
    //查詢
    public ResultSet executeQuery(String sql,Object...objects) throws Exception{
        getConnection();
        ps=con.prepareStatement(sql);
        for (int i = 0; i < objects.length; i++) {
            ps.setObject(i+1, objects[i]);
        }
        rSet = ps.executeQuery();
        return rSet;
        
    }
    
    //釋放資源
    public void closeResource(){
        try {
            if (rSet!=null) {
                 rSet.close();
             }
                if (ps!=null) {
                 ps.close();
             }
                if (con!=null) {
                 con.close();
             }
     } catch (Exception e) {
         e.printStackTrace();
     }
       
    }
}

接口:

public interface INewsDAO {
    public List<News> findAll() throws Exception;
}

實現用戶操做相關的類:

public class News {
     public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    private int id; //編號
     private String name; //姓名      
     private Date createTime;//時間
     private String content;
     public String author;
}
 

鏈接dao層和test層的關係:

實現接口

public class NewsServiceImpl implements INewsService {   
INewsDAO aa=new NewsDAOImpl(); @Override public List<News> findAll() throws Exception { return aa.findAll(); } }

定義接口:

public interface INewsService {
    public List<News> findAll() throws Exception;
}

mian方法:

    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
    NewManager manager=new NewManager();
    manager.toHtml();
    }

}

io流:

    

    public void writeFile(String filePath,String str) throws Exception{
        OutputStreamWriter oStreamWriter = new OutputStreamWriter(new FileOutputStream(filePath), "GBK");
        oStreamWriter.write(str);
        oStreamWriter.close();
    }
 
    public  String  readerFile(String filePath) throws Exception{

        InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "GBK");
        char[] ch = new char[1024];
        int data = 0;
        String str = null;
        StringBuffer sb = new StringBuffer();
        while ((data = isr.read(ch)) != -1) {
            str = new String(ch, 0, data);
            sb.append(str);
        }
        System.out.println(sb.toString());
        isr.close();
        return str;
    }


    
}

調用IO實現 html:

  public void toHtml() throws Exception{
          FileIo fileio= new FileIo();
          String templatestr=fileio.readerFile("F:\\JDBC_CMS\\src\\news.template");
          INewsService service=new NewsServiceImpl();
          List<News> newlist=service.findAll();
          for (int i = 0; i < newlist.size(); i++) {
            News news=newlist.get(i);
            String rep=new String();
            rep=templatestr;
            rep=rep.replace("{title}", news.getName());
            rep=rep.replace("{author}", news.getAuthor());
            rep=rep.replace("{createTime}", news.getCreateTime().toString());
            rep=rep.replace("{content}", news.getContent());
            
            String fil="F:\\哈哈哈+"+i+".html";
            fileio.writeFile(fil, rep);
        }
        }

}

 

實現結果:

相關文章
相關標籤/搜索