JSP新闻系统之二DAO框架

举报
tea_year 发表于 2021/12/29 23:49:13 2021/12/29
【摘要】 package com.news.util; import java.sql.*;import java.util.ArrayList;import java.util.List; //Dao工厂类public class DaoFactory { private static String driver = "com.microsof...

  
  1. package com.news.util;
  2. import java.sql.*;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. //Dao工厂类
  6. public class DaoFactory {
  7. private static String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
  8. private static String url = "jdbc:sqlserver://localhost:1433;DatabaseName=News";
  9. private static String user = "sa";
  10. private static String pwd = "123@qwe";
  11. // private static String driver="com.mysql.jdbc.Driver";
  12. // private static String url="jdbc:mysql://localhost:3306/news";
  13. // private static String user = "root" ;
  14. // private static String pwd = "admin" ;
  15. // 1.公共方法是获得数据库链接对象
  16. public static Connection getConnection() {
  17. Connection con = null;
  18. try {
  19. Class.forName(driver);// 加,连
  20. con = DriverManager.getConnection(url, user, pwd);
  21. } catch (ClassNotFoundException e) {
  22. e.printStackTrace();
  23. } catch (SQLException e) {
  24. e.printStackTrace();
  25. }
  26. return con;// 非void都需要return
  27. }
  28. // 2.关闭所有方法;有3个参数!,省代码了!!!
  29. public static void closeAll(ResultSet rs, Statement stmt, Connection con) {
  30. try {
  31. if (rs != null) {
  32. rs.close();
  33. }
  34. if (stmt != null) {
  35. stmt.close();
  36. }
  37. if (con != null) {
  38. con.close();
  39. }
  40. } catch (SQLException e) {
  41. e.printStackTrace();
  42. }
  43. }
  44. // 3.setParams,用来设置预编译语句对象的?占位符的值;
  45. public static void setParams(PreparedStatement pstmt, Object[] params) {
  46. if (params == null) {
  47. return;
  48. }// return:直接返回,啥也不做;
  49. try {
  50. for (int i = 0; i < params.length; i++) {
  51. pstmt.setObject(i + 1, params[i]);
  52. }
  53. } catch (SQLException e) {// 有异常,加上去
  54. e.printStackTrace();
  55. }
  56. }
  57. // 4.做公共的更新方法,可以更新所有的基本sql语句;
  58. public int executeUpdate(String sql, Object[] params) {
  59. // 1.声明对象;是将来工作当中省内存;
  60. Connection con = null;
  61. PreparedStatement pstmt = null;
  62. int count = 0; // 增删改受影响的行数;
  63. try {
  64. con = this.getConnection();// 调用本类的方法;
  65. pstmt = con.prepareStatement(sql);// 建对象:预编译对象,?
  66. setParams(pstmt, params);// 调用设置?的方法,已经写过了!!!
  67. count = pstmt.executeUpdate();// 3.执行;
  68. } catch (SQLException e) {
  69. e.printStackTrace();
  70. } finally {
  71. this.closeAll(null, pstmt, con);
  72. }
  73. return count;
  74. }
  75. // 5.执行查询方法;
  76. public static List executeQuery(String sql, Object[] params) {
  77. Connection con = null;
  78. PreparedStatement pstmt = null;
  79. ResultSet rs = null;
  80. int colCount = 0;
  81. ArrayList tableList=new ArrayList();//表集合
  82. try {
  83. con = getConnection();
  84. pstmt = con.prepareStatement(sql);
  85. setParams(pstmt, params);
  86. rs = pstmt.executeQuery();// 执行查询,结果给rs
  87. ResultSetMetaData rd = rs.getMetaData();// 获得元数据
  88. colCount = rd.getColumnCount();
  89. while (rs.next()) {
  90. ArrayList rowList = new ArrayList();//行集合
  91. for (int i = 1; i <= colCount; i++) {
  92. rowList.add(rs.getString(i));
  93. }
  94. tableList.add(rowList);
  95. }
  96. } catch (SQLException e) {
  97. e.printStackTrace();
  98. }finally{
  99. closeAll(rs,pstmt,con);
  100. }
  101. return tableList;
  102. }
  103. }


  
  1. package com.news.dao;
  2. import java.util.List;
  3. import com.news.entity.User;
  4. /**
  5. * 用户访问接口
  6. * @author Administrator
  7. *
  8. */
  9. public interface UserDao {
  10. public List<User> getAllUser();//查询所有用户
  11. public boolean saveUser(String username,String pwd,String email,String address,String bobby);
  12. public User queryUserByNameAndPwd(String username,String userpwd);//根据用户名和密码来查询用户是否存在;
  13. //通过查询获取数据表中数据总条数;
  14. public int getCount();
  15. //根据当前页码和页数,来分页的方法;返回User集合;
  16. public List<User>queryUserByPage(int currentPage,int pageSize);
  17. }


  
  1. package com.news.dao;
  2. import java.util.List;
  3. import com.news.entity.Topic;
  4. public interface TopicDao {
  5. public List<Topic> getAllTopic();//获得所有栏目
  6. public int addTopic(String tname); //实现类和接口方法务必一致;!
  7. public boolean deleteTopicById(int id);//根据ID删除主题栏目;
  8. //更新主题,先根据ID找到该主题;
  9. //根据ID查询一条主题记录
  10. Topic queryTopicById(int id);
  11. //根据ID修改一条记录
  12. public int updateTopicById(int id,String tname);
  13. }


  
  1. package com.news.dao;
  2. import java.util.List;
  3. import com.news.entity.News;
  4. /**
  5. * News接口
  6. * @author Administrator
  7. *
  8. */
  9. public interface NewsDao {
  10. List<News>queryNews();
  11. public int addNews(News news);//使用实体类进行传输数据;
  12. //根据新闻主题查询新闻
  13. public List<News>queryNewsByTopicId(int topicId);
  14. public News queryNewsById(int id);
  15. }


//实体类User,News,Topic等暂时省略


  
  1. package com.news.dao.impl;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import java.sql.*;
  5. import com.news.dao.UserDao;
  6. import com.news.entity.User;
  7. import com.news.util.DaoFactory;
  8. public class UserDaoImpl implements UserDao{
  9. @Override
  10. public List<User> getAllUser() {
  11. Connection con=null;
  12. Statement st=null;
  13. ResultSet rs=null;
  14. List<User>users=null;//利用泛型来创建users集合
  15. String sql="select * from t_user";
  16. //获得数据库的代码
  17. try {
  18. con=DaoFactory.getConnection();//贾琏
  19. st=con.createStatement();//语句对象;
  20. rs=st.executeQuery(sql);//执行结果;
  21. //遍历结果集

  
  1. users=new ArrayList<User>();
  2. while(rs.next()){
  3. //从数据库取出数据,然后再把数据库放入实体对象中;
  4. User user=new User();
  5. user.setId(rs.getInt("id"));
  6. user.setUsername(rs.getString("username"));
  7. user.setPwd(rs.getString("pwd"));
  8. user.setEmail(rs.getString("email"));
  9. user.setHobby(rs.getString("hobby"));
  10. user.setAddress(rs.getString("address"));
  11. users.add(user);
  12. }
  13. //users=DaoFactory.executeQuery(sql, null);
  14. } catch (Exception e) {
  15. e.printStackTrace();
  16. }finally{
  17. //操作结束
  18. DaoFactory.closeAll(rs, st, con);
  19. }
  20. return users;//返回user的集合
  21. }
  22. @Override
  23. public boolean saveUser(String username, String pwd, String email,
  24. String address, String bobby) {
  25. Connection con=null;
  26. PreparedStatement pstmt=null;
  27. boolean flag=false;
  28. //String sql="insert into t_user values(null,?,?,?,?,?)";//mysql格式;
  29. String sql="insert t_user values(?,?,?,?,?)";
  30. try {
  31. con=DaoFactory.getConnection();
  32. pstmt=con.prepareStatement(sql);
  33. Object[]params={username,pwd,email,address,bobby};
  34. DaoFactory.setParams(pstmt, params);
  35. pstmt.executeUpdate();
  36. flag=true;//成功则为true;
  37. } catch (SQLException e) {
  38. e.printStackTrace();
  39. }finally{
  40. DaoFactory.closeAll(null, pstmt, con);
  41. }
  42. return flag;
  43. }
  44. @Override
  45. public User queryUserByNameAndPwd(String username, String userpwd) {
  46. Connection con=null;
  47. PreparedStatement pstmt=null;
  48. ResultSet rs=null;
  49. User user=null;
  50. String sql="select * from t_user where username=? and pwd=?";
  51. try {
  52. con=DaoFactory.getConnection();
  53. pstmt=con.prepareStatement(sql);
  54. Object[]params={username,userpwd};
  55. DaoFactory.setParams(pstmt, params);
  56. rs=pstmt.executeQuery();
  57. while(rs.next()){
  58. user=new User();
  59. user.setId(rs.getInt("id"));
  60. user.setUsername(rs.getString("username"));
  61. user.setPwd(rs.getString("pwd"));
  62. user.setEmail(rs.getString("email"));
  63. user.setHobby(rs.getString("hobby"));
  64. user.setAddress(rs.getString("address"));
  65. }
  66. } catch (SQLException e) {
  67. e.printStackTrace();
  68. }finally{
  69. DaoFactory.closeAll(rs, pstmt, con);
  70. }
  71. return user;
  72. }
  73. /* 获得user的总个数,即要分页的总记录数
  74. * @see com.news.dao.UserDao#getCount()
  75. */
  76. @Override
  77. public int getCount() {
  78. Connection con=null;
  79. Statement st=null;
  80. ResultSet rs=null;
  81. int count=0;
  82. try {
  83. con=DaoFactory.getConnection();
  84. st=con.createStatement();
  85. String sql="select count(*) from t_user";
  86. rs=st.executeQuery(sql);
  87. if(rs.next()){
  88. count=rs.getInt(1);
  89. }
  90. } catch (SQLException e) {
  91. e.printStackTrace();
  92. }finally{
  93. DaoFactory.closeAll(rs, st, con);
  94. }
  95. return count;
  96. }
  97. @Override
  98. public List<User> queryUserByPage(int currentPage, int pageSize) {
  99. Connection con=null;
  100. Statement st=null;
  101. ResultSet rs=null;
  102. List<User>users=null;
  103. try {
  104. con=DaoFactory.getConnection();
  105. st=con.createStatement();
  106. users=new ArrayList<User>();
  107. 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";
  108. rs=st.executeQuery(sql);
  109. //遍历结果集
  110. while(rs.next()){
  111. //从数据库中取出一条记录后,放到实体对象中;
  112. User user=new User();
  113. user.setId(rs.getInt("id"));
  114. user.setUsername(rs.getString("username"));
  115. user.setEmail(rs.getString("email"));
  116. user.setAddress(rs.getString("address"));
  117. user.setHobby(rs.getString("hobby"));
  118. //将实体对象放入集合中;
  119. users.add(user);
  120. }
  121. } catch (SQLException e) {
  122. e.printStackTrace();
  123. }finally{
  124. DaoFactory.closeAll(rs, st, con);
  125. }
  126. return users;
  127. }
  128. }


  
  1. package com.news.dao.impl;
  2. import java.sql.*;
  3. import java.util.*;
  4. import com.news.dao.TopicDao;
  5. import com.news.entity.Topic;
  6. import com.news.util.DaoFactory;
  7. public class TopicDaoImpl implements TopicDao {
  8. @Override
  9. public List<Topic> getAllTopic(){
  10. Connection con=null;
  11. Statement st=null;
  12. ResultSet rs=null;
  13. String sql="select * from t_topic";
  14. List<Topic>topices=new ArrayList<Topic>();
  15. try {
  16. con=DaoFactory.getConnection();
  17. st=con.createStatement();
  18. rs=st.executeQuery(sql);
  19. while(rs.next()){
  20. Topic topic=new Topic();
  21. topic.setId(rs.getInt("id"));
  22. topic.setTname(rs.getString("tname"));
  23. topic.setCreatetime(rs.getDate("createtime"));
  24. topices.add(topic);
  25. }
  26. } catch (SQLException e) {
  27. e.printStackTrace();
  28. }finally{
  29. DaoFactory.closeAll(rs, st, con);
  30. }
  31. return topices;
  32. }
  33. @Override
  34. public int addTopic(String tname) {
  35. Connection con=null;
  36. PreparedStatement pstmt=null;
  37. String sql="insert t_topic values(?,getDate())";
  38. int result=0;
  39. try {
  40. con=DaoFactory.getConnection();
  41. pstmt=con.prepareStatement(sql);
  42. Object[]params={tname};
  43. DaoFactory.setParams(pstmt, params);
  44. result=pstmt.executeUpdate();
  45. } catch (SQLException e) {
  46. e.printStackTrace();
  47. }finally{
  48. DaoFactory.closeAll(null, pstmt, con);
  49. }
  50. return result;
  51. }
  52. /* 需要注意,存在关联删除的情况,如何报错!本处没有做处理!
  53. * @see com.news.dao.TopicDao#deleteTopicById(int)
  54. */
  55. @Override
  56. public boolean deleteTopicById(int id) {
  57. Connection con=null;
  58. Statement st=null;
  59. boolean flag=false;
  60. String sql="delete from t_topic where id="+id;
  61. try {
  62. con=DaoFactory.getConnection();
  63. st=con.createStatement();
  64. st.executeUpdate(sql);
  65. flag=true;
  66. } catch (SQLException e) {
  67. e.printStackTrace();
  68. }finally{
  69. DaoFactory.closeAll(null, st, con);
  70. }
  71. return flag;
  72. }
  73. @Override
  74. public Topic queryTopicById(int id) {
  75. Connection con=null;
  76. Statement st=null;
  77. ResultSet rs=null;
  78. Topic topic=null;
  79. try {
  80. con=DaoFactory.getConnection();
  81. st=con.createStatement();
  82. String sql="select * FROM t_topic where id="+id;
  83. rs=st.executeQuery(sql);
  84. while(rs.next()){
  85. topic=new Topic();
  86. topic.setId(rs.getInt("id"));
  87. topic.setTname(rs.getString("tname"));
  88. }
  89. } catch (SQLException e) {
  90. e.printStackTrace();
  91. }finally{
  92. DaoFactory.closeAll(rs, st, con);
  93. }
  94. return topic;
  95. }
  96. @Override
  97. public int updateTopicById(int id, String tname) {
  98. Connection con=null;
  99. PreparedStatement pstmt=null;
  100. int result=0;
  101. String sql="update t_topic set tname=? where id=?";
  102. try {
  103. con=DaoFactory.getConnection();
  104. pstmt=con.prepareStatement(sql);
  105. Object[]params={tname,id};
  106. DaoFactory.setParams(pstmt, params);
  107. result=pstmt.executeUpdate();
  108. } catch (SQLException e) {
  109. e.printStackTrace();
  110. }finally{
  111. DaoFactory.closeAll(null, pstmt, con);
  112. }
  113. return result;
  114. }
  115. }


  
  1. package com.news.dao.impl;
  2. import java.util.*;
  3. import java.util.Date;
  4. import java.sql.*;
  5. import com.news.dao.NewsDao;
  6. import com.news.entity.News;
  7. import com.news.util.DaoFactory;
  8. /**
  9. * NewsDao的实现类,可以对新闻实现查询;
  10. * @author Administrator
  11. *
  12. */
  13. public class NewsDaoImpl implements NewsDao {
  14. @Override
  15. public List<News> queryNews() {
  16. Connection con=null;
  17. Statement st=null;
  18. ResultSet rs=null;
  19. List<News>newses=new ArrayList<News>();
  20. String sql="select * from t_news";
  21. try {
  22. con=DaoFactory.getConnection();
  23. st=con.createStatement();
  24. rs=st.executeQuery(sql);
  25. while(rs.next()){
  26. News news=new News();
  27. news.setId(rs.getInt("id"));
  28. news.setTitle(rs.getString("title"));
  29. news.setAuthor(rs.getString("author"));
  30. news.setCreatetime(rs.getDate("createtime"));
  31. news.setModifyTime(rs.getDate("modifytime"));
  32. news.setNcontent(rs.getString("ncontent"));
  33. news.setSummary(rs.getString("summary"));
  34. news.setTid(rs.getInt("tid"));
  35. newses.add(news);
  36. }
  37. } catch (SQLException e) {
  38. e.printStackTrace();
  39. }finally{
  40. DaoFactory.closeAll(rs, st, con);
  41. }
  42. return newses;
  43. }
  44. @Override
  45. public int addNews(News news) {
  46. Connection con=null;
  47. PreparedStatement pstmt=null;
  48. int result=0;
  49. String sql="insert t_news values(?,?,?,getdate(),?,getdate(),?,null)";
  50. try {
  51. con=DaoFactory.getConnection();
  52. pstmt=con.prepareStatement(sql);
  53. Object[]params={news.getTid(),news.getTitle(),news.getAuthor(),news.getNcontent(),news.getSummary()};
  54. DaoFactory.setParams(pstmt, params);
  55. result=pstmt.executeUpdate();
  56. } catch (SQLException e) {
  57. e.printStackTrace();
  58. }finally{
  59. DaoFactory.closeAll(null, pstmt, con);
  60. }
  61. return result;
  62. }
  63. @Override
  64. public List<News> queryNewsByTopicId(int topicId) {
  65. Connection con=null;
  66. Statement st=null;
  67. ResultSet rs=null;
  68. List<News>newes=null;
  69. try {
  70. con=DaoFactory.getConnection();
  71. st=con.createStatement();
  72. newes=new ArrayList<News>();
  73. //根据主题id进行查询;
  74. String sql="select top 5 * from t_news where tid="+topicId+" order by createtime desc";
  75. rs=st.executeQuery(sql);
  76. while(rs.next()){
  77. //从数据库取出一条记录后,然后把数据放入实体对象中;
  78. News news=new News();
  79. news.setId(rs.getInt("id"));
  80. news.setTitle(rs.getString("title"));
  81. news.setAuthor(rs.getString("author"));
  82. //放入集合中;
  83. newes.add(news);
  84. }
  85. } catch (SQLException e) {
  86. e.printStackTrace();
  87. }finally{
  88. DaoFactory.closeAll(rs, st, con);
  89. }
  90. return newes;
  91. }
  92. @Override
  93. public News queryNewsById(int id) {
  94. Connection con=null;
  95. Statement st=null;
  96. ResultSet rs=null;
  97. News news=null;
  98. try {
  99. con=DaoFactory.getConnection();
  100. st=con.createStatement();
  101. String sql="select * from t_news where id="+id;
  102. rs=st.executeQuery(sql);
  103. while(rs.next()){
  104. news=new News();
  105. news.setId(rs.getInt("id"));
  106. news.setTitle(rs.getString("title"));
  107. news.setNcontent(rs.getString("ncontent"));
  108. news.setAuthor(rs.getString("author"));
  109. news.setCreatetime(rs.getDate("createtime"));
  110. }
  111. } catch (SQLException e) {
  112. e.printStackTrace();
  113. }finally{
  114. DaoFactory.closeAll(rs, st, con);
  115. }
  116. return news;
  117. }
  118. }


文章来源: aaaedu.blog.csdn.net,作者:tea_year,版权归原作者所有,如需转载,请联系作者。

原文链接:aaaedu.blog.csdn.net/article/details/53044405

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。