JSP 뉴스 시스템의 2DAO 프레임워크

15292 단어 fontclassWOW_T
package com.news.util;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

//Dao   
public class DaoFactory {
	private static String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
	private static String url = "jdbc:sqlserver://localhost:1433;DatabaseName=News";
	private static String user = "sa";
	private static String pwd = "123@qwe";
	
//	private static String driver="com.mysql.jdbc.Driver";
//	private static String url="jdbc:mysql://localhost:3306/news";
//    private static String user = "root" ;   
//    private static String pwd = "admin" ;  
    
	// 1.              
	public static Connection getConnection() {
		Connection con = null;
		try {
			Class.forName(driver);//  , 
			con = DriverManager.getConnection(url, user, pwd);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return con;//  void   return
	}
	// 2.      ; 3   !,    !!!
	public static void closeAll(ResultSet rs, Statement stmt, Connection con) {
		try {
			if (rs != null) {
				rs.close();
			}
			if (stmt != null) {
				stmt.close();
			}
			if (con != null) {
				con.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	// 3.setParams,            ?     ;
	public static void setParams(PreparedStatement pstmt, Object[] params) {
		if (params == null) {
			return;
		}// return:    ,    ;
		try {
			for (int i = 0; i < params.length; i++) {
				pstmt.setObject(i + 1, params[i]);
			}
		} catch (SQLException e) {//    ,   
			e.printStackTrace();
		}
	}

	// 4.        ,         sql  ;
	public int executeUpdate(String sql, Object[] params) {
		// 1.    ;          ;
		Connection con = null;
		PreparedStatement pstmt = null;
		int count = 0; //          ;

		try {
			con = this.getConnection();//        ;
			pstmt = con.prepareStatement(sql);//    :     ,?
			setParams(pstmt, params);//     ?   ,     !!!
			count = pstmt.executeUpdate();// 3.  ;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			this.closeAll(null, pstmt, con);
		}
		return count;
	}

	// 5.      ;
	public static List executeQuery(String sql, Object[] params) {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		int colCount = 0;
		ArrayList tableList=new ArrayList();//   
		
		try {
			con = getConnection();
			pstmt = con.prepareStatement(sql);
			setParams(pstmt, params);
			rs = pstmt.executeQuery();//     ,   rs
			ResultSetMetaData rd = rs.getMetaData();//      
			colCount = rd.getColumnCount();
			while (rs.next()) {
				ArrayList rowList = new ArrayList();//   
				for (int i = 1; i <= colCount; i++) {
					rowList.add(rs.getString(i));
				}
				tableList.add(rowList);				
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			closeAll(rs,pstmt,con);
		}
		return tableList;
	}
}
package com.news.dao;

import java.util.List;

import com.news.entity.User;

/**
 *       
 * @author Administrator
 *
 */
public interface UserDao {
	public List<User> getAllUser();//      
	public boolean saveUser(String username,String pwd,String email,String address,String bobby);
	public User queryUserByNameAndPwd(String username,String userpwd);//                 ;
	//               ;
	public int getCount();
	//         ,      ;  User  ;
	public List<User>queryUserByPage(int currentPage,int pageSize);
}
package com.news.dao;

import java.util.List;

import com.news.entity.Topic;

public interface TopicDao {
	public List<Topic> getAllTopic();//      
	public int addTopic(String tname); //            ;!
	public boolean deleteTopicById(int id);//  ID      ;
	
	//    ,   ID     ;
	//  ID        
	Topic queryTopicById(int id);
	//  ID      
	public int updateTopicById(int id,String tname);
}
package com.news.dao;

import java.util.List;

import com.news.entity.News;

/**
 * News  
 * @author Administrator
 *
 */
public interface NewsDao {
	List<News>queryNews();
	public int addNews(News news);//           ;
	//          
	public List<News>queryNewsByTopicId(int topicId);
	public News queryNewsById(int id);
}

//솔리드 클래스 User, News, Topic 등은 잠시 생략
package com.news.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.sql.*;

import com.news.dao.UserDao;
import com.news.entity.User;
import com.news.util.DaoFactory;

public class UserDaoImpl implements UserDao{
	@Override
	public List<User> getAllUser() {
		Connection con=null;
		Statement st=null;
		ResultSet rs=null;
		List<User>users=null;//       users  
		String sql="select * from t_user";
		//        
		try {
			con=DaoFactory.getConnection();//  
			st=con.createStatement();//    ;
			rs=st.executeQuery(sql);//    ;
			//     
                         users=new ArrayList<User>();

			while(rs.next()){
				//        ,              ;
				User user=new User();
				user.setId(rs.getInt("id"));
				user.setUsername(rs.getString("username"));
				user.setPwd(rs.getString("pwd"));
				user.setEmail(rs.getString("email"));
				user.setHobby(rs.getString("hobby"));
				user.setAddress(rs.getString("address"));

				users.add(user);
		}
			//users=DaoFactory.executeQuery(sql, null);
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			//    
			DaoFactory.closeAll(rs, st, con);
		}
		return users;//  user   
	}

	@Override
	public boolean saveUser(String username, String pwd, String email,
			String address, String bobby) {
		Connection con=null;
		PreparedStatement pstmt=null;
		boolean flag=false;
		//String sql="insert into t_user values(null,?,?,?,?,?)";//mysql  ;
		String sql="insert t_user values(?,?,?,?,?)";
		
		try {
			con=DaoFactory.getConnection();		
			pstmt=con.prepareStatement(sql);
			Object[]params={username,pwd,email,address,bobby};
			DaoFactory.setParams(pstmt, params);
			pstmt.executeUpdate();
			flag=true;//    true;
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DaoFactory.closeAll(null, pstmt, con);
		}
		return flag;
	}

	@Override
	public User queryUserByNameAndPwd(String username, String userpwd) {
		Connection con=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		User user=null;
		String sql="select * from t_user where username=? and pwd=?";
		
		try {
			con=DaoFactory.getConnection();
			pstmt=con.prepareStatement(sql);
			Object[]params={username,userpwd};
			DaoFactory.setParams(pstmt, params);
			rs=pstmt.executeQuery();
			while(rs.next()){
				user=new User();
				user.setId(rs.getInt("id"));
				user.setUsername(rs.getString("username"));
				user.setPwd(rs.getString("pwd"));
				user.setEmail(rs.getString("email"));
				user.setHobby(rs.getString("hobby"));
				user.setAddress(rs.getString("address"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DaoFactory.closeAll(rs, pstmt, con);
		}
		return user;
	}

	/*   user    ,         
	 * @see com.news.dao.UserDao#getCount()
	 */
	@Override
	public int getCount() {
		Connection con=null;
		Statement st=null;
		ResultSet rs=null;
		int count=0;
		
		try {
			con=DaoFactory.getConnection();
			st=con.createStatement();
			String sql="select count(*) from t_user";
			rs=st.executeQuery(sql);
			if(rs.next()){
				count=rs.getInt(1);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DaoFactory.closeAll(rs, st, con);
		}
		return count;
	}

	@Override
	public List<User> queryUserByPage(int currentPage, int pageSize) {
		Connection con=null;
		Statement st=null;
		ResultSet rs=null;
		List<User>users=null;
		
		try {
			con=DaoFactory.getConnection();
			st=con.createStatement();
			users=new ArrayList<User>();
			String sql="select top "+pageSize+" * from t_user where id not in (select top "+(currentPage-1)*pageSize+" id from t_user order by id)order by id";
			rs=st.executeQuery(sql);
			//     
			while(rs.next()){
				//            ,       ;
				User user=new User();
				user.setId(rs.getInt("id"));
				user.setUsername(rs.getString("username"));
				user.setEmail(rs.getString("email"));
				user.setAddress(rs.getString("address"));
				user.setHobby(rs.getString("hobby"));
				//          ;
				users.add(user);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DaoFactory.closeAll(rs, st, con);
		}
		return users;
	}
	
}
package com.news.dao.impl;

import java.sql.*;
import java.util.*;

import com.news.dao.TopicDao;
import com.news.entity.Topic;
import com.news.util.DaoFactory;

public class TopicDaoImpl implements TopicDao {

	@Override
	public List<Topic> getAllTopic(){
		Connection con=null;
		Statement st=null;
		ResultSet rs=null;
		String sql="select * from t_topic";
		List<Topic>topices=new ArrayList<Topic>();
		
		try {
			con=DaoFactory.getConnection();
			st=con.createStatement();
			rs=st.executeQuery(sql);
			while(rs.next()){
				Topic topic=new Topic();
				topic.setId(rs.getInt("id"));
				topic.setTname(rs.getString("tname"));
				topic.setCreatetime(rs.getDate("createtime"));
				
				topices.add(topic);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DaoFactory.closeAll(rs, st, con);
		}
		return topices;		
	}

	@Override
	public int addTopic(String tname) {
		Connection con=null;
		PreparedStatement pstmt=null;
		String sql="insert t_topic values(?,getDate())";
		int result=0;
		
		try {
			con=DaoFactory.getConnection();
			pstmt=con.prepareStatement(sql);
			Object[]params={tname};
			DaoFactory.setParams(pstmt, params);
			result=pstmt.executeUpdate();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DaoFactory.closeAll(null, pstmt, con);
		}
		return result;
	}

	/*     ,         ,    !       !
	 * @see com.news.dao.TopicDao#deleteTopicById(int)
	 */
	@Override
	public boolean deleteTopicById(int id) {
		Connection con=null;
		Statement st=null;
		boolean flag=false;
		String sql="delete from t_topic where id="+id;
		try {
			con=DaoFactory.getConnection();
			st=con.createStatement();
			st.executeUpdate(sql);
			flag=true;
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DaoFactory.closeAll(null, st, con);
		}
		return flag;
	}

	@Override
	public Topic queryTopicById(int id) {
		Connection con=null;
		Statement st=null;
		ResultSet rs=null;
		Topic topic=null;
		
		try {
			con=DaoFactory.getConnection();
			st=con.createStatement();
			String sql="select * FROM t_topic where id="+id;
			rs=st.executeQuery(sql);
			while(rs.next()){
				topic=new Topic();
				topic.setId(rs.getInt("id"));
				topic.setTname(rs.getString("tname"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DaoFactory.closeAll(rs, st, con);
		}
		return topic;
	}

	@Override
	public int updateTopicById(int id, String tname) {
		Connection con=null;
		PreparedStatement pstmt=null;
		int result=0;
		String sql="update t_topic set tname=? where id=?";
		
		try {
			con=DaoFactory.getConnection();
			pstmt=con.prepareStatement(sql);
			Object[]params={tname,id};
			DaoFactory.setParams(pstmt, params);
			result=pstmt.executeUpdate();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DaoFactory.closeAll(null, pstmt, con);
		}
		return result;
	}
}
package com.news.dao.impl;

import java.util.*;
import java.util.Date;
import java.sql.*;

import com.news.dao.NewsDao;
import com.news.entity.News;
import com.news.util.DaoFactory;

/**
 * NewsDao    ,         ;
 * @author Administrator
 *
 */

public class NewsDaoImpl implements NewsDao {

	@Override
	public List<News> queryNews() {
		Connection con=null;
		Statement st=null;
		ResultSet rs=null;
		List<News>newses=new ArrayList<News>();
		String sql="select * from t_news";
		try {
			con=DaoFactory.getConnection();
			st=con.createStatement();
			rs=st.executeQuery(sql);
			while(rs.next()){
				News news=new News();
				news.setId(rs.getInt("id"));
				news.setTitle(rs.getString("title"));
				news.setAuthor(rs.getString("author"));
				news.setCreatetime(rs.getDate("createtime"));
				news.setModifyTime(rs.getDate("modifytime"));
				news.setNcontent(rs.getString("ncontent"));
				news.setSummary(rs.getString("summary"));
				news.setTid(rs.getInt("tid"));
				
				newses.add(news);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DaoFactory.closeAll(rs, st, con);
		}
		return newses;
	}

	@Override
	public int addNews(News news) {
		Connection con=null;
		PreparedStatement pstmt=null;
		int result=0;
		String sql="insert t_news values(?,?,?,getdate(),?,getdate(),?,null)";
		
		try {
			con=DaoFactory.getConnection();
			pstmt=con.prepareStatement(sql);
			Object[]params={news.getTid(),news.getTitle(),news.getAuthor(),news.getNcontent(),news.getSummary()};
			DaoFactory.setParams(pstmt, params);
			result=pstmt.executeUpdate();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DaoFactory.closeAll(null, pstmt, con);
		}
		return result;
	}

	@Override
	public List<News> queryNewsByTopicId(int topicId) {
		Connection con=null;
		Statement st=null;
		ResultSet rs=null;
		List<News>newes=null;
		
		try {
			con=DaoFactory.getConnection();
			st=con.createStatement();
			newes=new ArrayList<News>();
			//    id    ;
			String sql="select top 5 * from t_news where tid="+topicId+" order by createtime desc";
			rs=st.executeQuery(sql);
			while(rs.next()){
				//           ,            ;
				News news=new News();
				news.setId(rs.getInt("id"));
				news.setTitle(rs.getString("title"));
				news.setAuthor(rs.getString("author"));
				//     ;
				newes.add(news);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DaoFactory.closeAll(rs, st, con);
		}
		return newes;
	}

	@Override
	public News queryNewsById(int id) {
		Connection con=null;
		Statement st=null;
		ResultSet rs=null;
		News news=null;
		
		try {
			con=DaoFactory.getConnection();
			st=con.createStatement();
			String sql="select * from t_news where id="+id;
			rs=st.executeQuery(sql);
			while(rs.next()){
				news=new News();
				news.setId(rs.getInt("id"));
				news.setTitle(rs.getString("title"));
				news.setNcontent(rs.getString("ncontent"));
				news.setAuthor(rs.getString("author"));
				news.setCreatetime(rs.getDate("createtime"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DaoFactory.closeAll(rs, st, con);
		}
		return news;
	}
}

좋은 웹페이지 즐겨찾기