html(四)数据库curd操作与分页查询

数据库操作curd :

1.首先要建立项目处理好自己逻辑包:

其中util工具包中建立两个工具类 jdbc连接和page分页

DBUtil.java:

db工具类就是用于连接数据库的jdbc架包,里面是curd的实现。

  1 package com.etc.utils;
  2 
  3 import java.sql.Connection;
  4 import java.sql.DriverManager;
  5 import java.sql.PreparedStatement;
  6 import java.sql.ResultSet;
  7 import java.sql.SQLException;
  8 
  9 import javax.sql.rowset.CachedRowSet;
 10 
 11 import com.sun.rowset.CachedRowSetImpl;
 12 
 13 /**
 14  * 数据库访问的通用类
 15  * 
 16  * @author Administrator
 17  * 
 18  */
 19 public class DBUtil {
 20     private final static String URL = "jdbc:mysql://localhost/day07";
 21     private final static String USER = "root";
 22     private final static String PASSWORD = "123456";
 23     private final static String DRIVER = "com.mysql.jdbc.Driver";
 24 
 25     /**
 26      * 定义方法返回一个连接(Connection)对象
 27      * 
 28      * @return 返回值就是一个连接对象
 29      */
 30     private static Connection getConnection() {
 31         Connection conn = null;
 32         try {
 33             Class.forName(DRIVER);
 34             conn = DriverManager.getConnection(URL, USER, PASSWORD);
 35         } catch (ClassNotFoundException e) {
 36             e.printStackTrace();
 37         } // 低版本的jdbc jar包
 38         catch (SQLException e) {
 39             e.printStackTrace();
 40         }
 41         return conn;
 42     }
 43 
 44     /**
 45      * 一个方法来做增加删除和修改
 46      * 
 47      * @param sql   要执行的sql
 48      * @param param 执行的sql中包含的参数的实际值
 49      * @return int 表示的是受影响的行
 50      */
 51     public static int execUpdate(String sql, Object... param) {
 52         Connection conn = getConnection();
 53         PreparedStatement pstmt = null;
 54         int result = 0;
 55         try {
 56             pstmt = conn.prepareStatement(sql);
 57             for (int i = 0; i < param.length; i++) {
 58                 pstmt.setObject(i + 1, param[i]);
 59             }
 60             result = pstmt.executeUpdate();
 61         } catch (SQLException e) {
 62             e.printStackTrace();
 63         } finally {
 64             closeAll(null, pstmt, conn);
 65         }
 66         return result;
 67     }
 68 
 69     /**
 70      * 一个方法来做查询
 71      * 
 72      * @param sql   要执行查询的sql语句
 73      * @param param 要执行sql对应的参数
 74      * @return CachedRowSet 缓存的结果集
 75      */
 76     public static CachedRowSet execQuery(String sql, Object... param) {
 77         Connection conn = getConnection();
 78         PreparedStatement pstmt = null;
 79         ResultSet rs = null;
 80         // 实例化CachedRowSetImpl
 81         CachedRowSetImpl crs = null;
 82         try {
 83             crs = new CachedRowSetImpl();
 84             pstmt = conn.prepareStatement(sql);
 85             // 可以吧param当成是一个数组
 86             System.out.println(param.length);
 87 
 88             for (int i = 0; i < param.length; i++) {
 89                 pstmt.setObject(i + 1, param[i]);
 90             }
 91             rs = pstmt.executeQuery();
 92             // 建立rs和crs关系,可以将rs的数据行缓存到crs中了
 93             crs.populate(rs);
 94         } catch (SQLException e) {
 95             e.printStackTrace();
 96         } finally {
 97             // 释放资源等 此处代码省略
 98             closeAll(rs, pstmt, conn);
 99         }
100         return crs;
101     }
102 
103     /**
104      * 释放资源
105      * 
106      * @param rs    结果集兑现
107      * @param pstmt 预处理语句对象
108      * @param conn  连接对象
109      */
110     private static void closeAll(ResultSet rs, PreparedStatement pstmt, Connection conn) {
111         try {
112             if (rs != null)
113                 rs.close();
114         } catch (SQLException e) {
115             e.printStackTrace();
116         }
117         try {
118             if (pstmt != null)
119                 pstmt.close();
120         } catch (SQLException e) {
121             e.printStackTrace();
122         }
123         try {
124             if (conn != null)
125                 conn.close();
126         } catch (SQLException e) {
127             e.printStackTrace();
128         }
129     }
130 
131 }
View Code

Page.java:

通过字段分页的总页数、总数、页面显示数、所有数据集合来实例化实现分页显示。

 1 package com.etc.utils;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 public class Page<T> {
 7         // 总页数
 8         private int totalPageCount = 1;
 9         // 页面大小,即每页显示记录数
10         private int pageSize = 10;
11         // 记录总数
12         private int totalCount = 0;
13         // 当前页码
14         private int currPageNo = 1;
15         // 每页集合
16         List<T> list = new ArrayList<>();
17         
18         public int getTotalPageCount() {
19             return totalPageCount;
20         }
21         public void setTotalPageCount(int totalPageCount) {
22             this.totalPageCount = totalPageCount;
23         }
24         public int getPageSize() {
25             return pageSize;
26         }
27         public void setPageSize(int pageSize) {
28             this.pageSize = pageSize;
29         }
30         public int getTotalCount() {
31             return totalCount;
32         }
33         public void setTotalCount(int totalCount) {
34             this.totalCount = totalCount;
35         }
36         public int getCurrPageNo() {
37             return currPageNo;
38         }
39         public void setCurrPageNo(int currPageNo) {
40             this.currPageNo = currPageNo;
41         }
42         public List<T> getList() {
43             return list;
44         }
45         public void setList(List<T> list) {
46             this.list = list;
47         }
48         
49         
50 }
View Code

User.java:

实现包 entityr User就是普通的user类定义了查询用户的id,username,password 根据自己数据库的表建立相对应的自段。

 1 package com.etc.entity;
 2 
 3 public class User {
 4     private int uid=0;
 5     private String username;
 6     private String password;
 7     
 8     public User(int uid, String username, String password) {
 9         super();
10         this.uid = uid;
11         this.username = username;
12         this.password = password;
13     }
14 
15     public User() {
16         super();
17     }
18 
19     public int getUid() {
20         return uid;
21     }
22 
23     public void setUid(int uid) {
24         this.uid = uid;
25     }
26 
27     public String getUsername() {
28         return username;
29     }
30 
31     public void setUsername(String username) {
32         this.username = username;
33     }
34 
35     public String getPassword() {
36         return password;
37     }
38 
39     public void setPassword(String password) {
40         this.password = password;
41     }
42     
43     
44     
45 }
View Code

数据库设计:

2.建立最重要的DAO层(数据访问层):

 因为传入的是User类 所以值都是user.get方法来获取界面传入的值:

DBUtil.execUpdate("insert into t_user(username,password) values(?,?)", user.getUsername(), user.getPassword());

登陆时需要验证账号密码是否正确,此时需要对数据库的数据进行验证,如果正确返回user对象,不正确则返回null:

UserDao:

 1 package com.etc.dao;
 2 
 3 import java.sql.SQLException;
 4 
 5 import javax.sql.rowset.CachedRowSet;
 6 
 7 import com.etc.entity.User;
 8 import com.etc.utils.DBUtil;
 9 import com.etc.utils.Page;
10 
11 public class UserDao {
12     //设置注册实现
13     public void reg(User user) {
14         //通过工具类DBUtil的execUpdate方法,传入sql和值(username,password)
15         DBUtil.execUpdate("insert into t_user(username,password) values(?,?)", user.getUsername(), user.getPassword());
16     }
17     //设置登陆实现
18     public User login(String username, String password) {
19         //传入你登陆要验证的账号密码,此时会通过sql语句来通过账号密码来判断是否存在 存在就继续向下执行 不存在就返回null
20         CachedRowSet rowSet = DBUtil.execQuery("select * from t_user where username=? and password=?", username,
21                 password);
22         try {
23             //循环获取值 直到账号密码全部一致
24             while (rowSet.next()) {
25                 //获取数据库的uid,username,password
26                 int uid = rowSet.getInt("uid");
27                 String username2 = rowSet.getString("username");
28                 String password2 = rowSet.getString("password");
29                 //将值传入新实例化的user对象中
30                 User user = new User(uid, username2, password2);
31                 //返回user对象
32                 return user;
33             }
34         } catch (SQLException e) {
35             e.printStackTrace();
36         }
37         return null;
38     }
39     //分页显示数据
40     public Page<User> queryByPage(Page<User> page) {
41         ///通过sql语句 count(1)计算数据中所有的所有数据总数
42         CachedRowSet rowSet = DBUtil.execQuery("select count(1) from t_user");
43         try {
44             //获取查询出来的总数
45             while (rowSet.next()) {
46                 //sql中默认将第一个值设置为第一列
47                 int total = rowSet.getInt(1);
48                 //将总数传入page中
49                 page.setTotalCount(total);
50             }
51         } catch (SQLException e) {
52             e.printStackTrace();
53         }
54         //通过sql语句限制查询的每页的数量      ( limit ?,? )方法    
55         //传入的值 (page.getCurrPageNo()-1)*page.getPageSize()   ,    page.getPageSize()
56         //             (页数-1)              * 显示的数量  
57         CachedRowSet rowSet2 = DBUtil.execQuery("select * from t_user limit ?,?", (page.getCurrPageNo()-1)*page.getPageSize(),page.getPageSize());
58 
59         try {
60             //循环遍历
61             while (rowSet2.next()) {
62                 int uid = rowSet2.getInt("uid");
63                 String username2 = rowSet2.getString("username");
64                 String password2 = rowSet2.getString("password");
65                 User user = new User(uid, username2, password2);
66                 //在page中的集合添加每个页面显示的值
67                 page.getList().add(user);
68             }
69         } catch (SQLException e) {
70             e.printStackTrace();
71         }
72         return page;
73     }
74 }

main.jsp:

 1 <%@page import="com.etc.entity.User"%>
 2 <%@page import="com.etc.utils.Page"%>
 3 <%@page import="com.etc.dao.UserDao"%>
 4 <%@ page language="java" contentType="text/html; charset=UTF-8"
 5     pageEncoding="UTF-8"%>
 6 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 7 <html>
 8 <head>
 9 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
10 <title>Insert title here</title>
11 </head>
12 <body>
13     <%
14         //实例化一个usredao和page才能使用其方法
15         UserDao userDao = new UserDao();
16         Page<User> pa = new Page<>();
17         
18         //获取页面默认返回值pageNo
19         String pageNo = request.getParameter("pageNo");
20         
21         //如果第一次登陆或者没登陆时 将显示的页面设为1
22         if (pageNo == null || "".equals(pageNo)) {
23             pa.setCurrPageNo(1);
24 
25         } else {
26             //如果不是第一次登陆 设置显示的值为你选择的值
27             pa.setCurrPageNo(Integer.valueOf(pageNo));
28         }
29 
30         //将page传入dao中
31         userDao.queryByPage(pa);
32 
33         //循环遍历分页集合中的值
34         for (User u : pa.getList()) {
35             out.print(u.getUid() + "," + u.getUsername() + "," + u.getPassword() + "<br>");
36         }
37     %>
38 
39     当前第<%=pa.getCurrPageNo()%>40     <br>
41     <%--将页面默认返回pageNo设置为pa.getCurrPageNo() - 1来设为当前页面的页面数  
42     从而传给userdao 来获取当前页数 计算需要遍历的行数为 0-10还是10-20 --%>
43     <a href="?pageNo=<%=pa.getCurrPageNo() - 1%>">上一页</a>
44     <a href="?pageNo=<%=pa.getCurrPageNo() + 1%>">下一页</a>
45 </body>
46 </html>

里面的注册 、登陆在上一篇已经提到了  所以这两篇可以合成一个项目 就是最上边显示的项目图。

猜你喜欢

转载自www.cnblogs.com/LiuOOP/p/11020182.html