DAO 模式四要素:介面、工廠、實現類、調用者。本文提供最簡單實現供初學者參考。
public interface NewsDAO {
News getNewsByPrimaryKey(int newsid) throws SQLException;
News[] getRecentNews();
News[] getHotNews();
}
public class NewsDAOMySQL implements NewsDAO {
private String url = "jdbc:mysql://localhost:3306/joke?user=root";
public NewsDAOMySQL() { /* 載入驅動 */ }
public News getNewsByPrimaryKey(int newsid) throws SQLException {
Connection conn = getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT newsid,title,content FROM news2 WHERE newsid=" + newsid);
News news = null;
if (rs.next()) news = new News(rs.getInt(1), rs.getString(2), rs.getString(3));
rs.close(); stmt.close(); conn.close();
return news;
}
private Connection getConnection() throws SQLException {
return DriverManager.getConnection(url);
}
}
工廠類根據配置返回具體實現,調用者透過介面使用,實現資料庫切換解耦。