当前位置:   article > 正文

JavaWeb学习笔记7——JDBC连接MySql进行增删改查并分页显示_利用jdbc实现数据库连接和增删改查操作,并在jsp页面中进行显示

利用jdbc实现数据库连接和增删改查操作,并在jsp页面中进行显示

 

数据库的增、删、改、查是非常重要的操作,只要程序是关于数据库的操作,无论程序大小,归根结底都是这4种操作的使用。

连接MySql数据库的过程:

1、注册驱动

DriverManager.registerDriver(new com.mysql.jdbc.Driver());

2、获取数据库连接

Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=UTF-8","数据库账号","数据库密码");

3、获取Statement

Statement stmt = conn.createStatement();

4、返回Resultset

ResultSet rs = stmt.executeQuery(sql);

 

下面的例子就是对MySql数据库进行连接并对tb_person表进行增、删、改、查。

本例子数据库名:databaseWeb,表名:tb_person

                                                                                listPagedPerson.jsp

  1. <%@page import="org.apache.jasper.tagplugins.jstl.core.Param"%>
  2. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"
  3. contentType="text/html;charset=UTF-8"%>
  4. <%@ page import="java.sql.Connection"%>
  5. <%@ page import="java.sql.ResultSet"%>
  6. <%@ page import="java.sql.Statement"%>
  7. <%@ page import="java.sql.DriverManager"%>
  8. <jsp:directive.page import="java.sql.Date" />
  9. <jsp:directive.page import="java.sql.Timestamp" />
  10. <jsp:directive.page import="java.sql.SQLException" />
  11. <jsp:directive.page import="java.sql.PreparedStatement" />
  12. <jsp:directive.page import="com.hedong.learn.Pagination" />
  13. <style>a{text-decoration:none}</style> <%--去掉页面超链接的注释 --%>
  14. <form action="listPagedPerson.jsp" method=get>
  15. <input type="hidden" name="action" value="search"> <%--执行查询操作 --%>
  16. <table align="center">
  17. <tr>
  18. <td>姓名</td>
  19. <td><input type="text" name='name' value="${param.name}" ></td>
  20. <td><input type="submit" value="查询"></td>
  21. </tr>
  22. </table>
  23. </form>
  24. <%
  25. final int pageSize = 5; //每页10条数据
  26. int pageNum = 1; //当前页数,默认从第一页开始
  27. int pageCount = 1; //总页数
  28. int recordCount = 0; //总共有多少条记录
  29. String action=request.getParameter("action");
  30. try {
  31. pageNum = Integer.parseInt(request.getParameter("pageNum"));//取当前页数
  32. } catch (Exception e) {
  33. }
  34. String sql = null;
  35. Connection conn = null;
  36. Statement stmt = null;
  37. ResultSet rs = null;
  38. try {
  39. if(!"search".equals(action))
  40. {
  41. conn=Pagination.getConnection();
  42. stmt = conn.createStatement();
  43. sql = "SELECT count(*) FROM tb_person "; //查询记录总数的sql语句
  44. rs = stmt.executeQuery(sql);
  45. if (rs.next()) {
  46. recordCount = rs.getInt(1);//获得记录总数
  47. }
  48. pageCount = (recordCount + pageSize - 1) / pageSize;//计算总页数
  49. int startRecord = (pageNum - 1) * pageSize; //计算本页记录从stratRecord开始
  50. sql = "Select * from tb_person LIMIT "+startRecord+","+pageSize;//此sql语句将记录进行分页
  51. rs = stmt.executeQuery(sql);
  52. }
  53. else if("search".equals(action))
  54. {
  55. String name=request.getParameter("name");//获得要查询的人的名字
  56. conn=Pagination.getConnection();
  57. sql="SELECT * FROM tb_person WHERE name='"+name+"'";
  58. stmt = conn.createStatement();
  59. rs = stmt.executeQuery(sql);
  60. }
  61. %>
  62. <form action="operatePerson.jsp" method=get>
  63. <table bgcolor="#CCCCCC" cellspacing=1 cellpadding=5 width=100%>
  64. <tr bgcolor=#DDDDDD>
  65. <th>序号</th>
  66. <th>姓名</th>
  67. <th>英文名</th>
  68. <th>性别</th>
  69. <th>年龄</th>
  70. <th>生日</th>
  71. <th>备注</th>
  72. <th>操作</th>
  73. </tr>
  74. <%
  75. int count=1;
  76. while (rs.next()) {
  77. //获得表中各数据
  78. int id = rs.getInt("id");
  79. int age = rs.getInt("age");
  80. String name = rs.getString("name");
  81. String englishName = rs.getString("english_name");
  82. String sex = rs.getString("sex");
  83. String description = rs.getString("description");
  84. Date birthday = rs.getDate("birthday");
  85. //将数据进行写出
  86. out.println("<tr bgcolor=#FFFFFF>");
  87. out.println("<td>" + count + "</td>");
  88. out.println("<td>" + name + "</td>");
  89. out.println("<td>" + englishName + "</td>");
  90. out.println("<td>" + sex + "</td>");
  91. out.println("<td>" + age + "</td>");
  92. out.println("<td>" + birthday + "</td>");
  93. out.println("<td>" + description + "</td>");
  94. out.println("<td>");
  95. out.println("<a href='operatePerson.jsp?action=del&id=" + id
  96. + "' onclick='return confirm(\"确定删除记录?\");'>删除</a>");
  97. out.println("<a href='operatePerson.jsp?action=edit&id=" + id + "'>修改</a>");
  98. out.println("</td");
  99. out.println("</tr>");
  100. count++;
  101. }
  102. %>
  103. <tr>
  104. <td colspan="2" align="left"><a href="addPerson.jsp">新建人员资料</a> <!-- 转到添加人员的页面 --></td>
  105. <td colspan="6" align="right"><%=Pagination.getPagination(pageNum, pageCount, recordCount, request.getRequestURI())%></td>
  106. </tr>
  107. </table>
  108. </form>
  109. <%
  110. } catch (SQLException e) {
  111. out.println("执行SQL:" + sql + "时发生异常:" + e.getMessage());
  112. e.printStackTrace();
  113. } finally {
  114. if (rs != null)
  115. rs.close();
  116. if (stmt != null)
  117. stmt.close();
  118. if (conn != null)
  119. conn.close();
  120. }
  121. %>
  122. </body>
  123. </html>

                                                                                    addPerson.jsp

  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"
  2. contentType="text/html;charset=UTF-8"%>
  3. <%
  4. String path = request.getContextPath();
  5. String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
  6. + path + "/";
  7. %>
  8. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  9. <%
  10. String action = (String) request.getAttribute("action");
  11. String id = (String) request.getAttribute("id");
  12. String name = (String) request.getAttribute("name");
  13. String englishName = (String) request.getAttribute("englishName");
  14. String age = (String) request.getAttribute("age");
  15. String sex = (String) request.getAttribute("sex");
  16. String birthday = (String) request.getAttribute("birthday");
  17. String description = (String) request.getAttribute("description");
  18. boolean isEdit = "edit".equals(action);//判断是修改还是添加操作
  19. %>
  20. <html>
  21. <head>
  22. <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
  23. <title><%=isEdit ? "修改人员资料" : "新建人员资料"%></title>
  24. <style type="text/css">
  25. body, td {
  26. font-size: 12px;
  27. }
  28. </style>
  29. </head>
  30. <body>
  31. <script type="text/javascript" src="js/calendar.js"></script>
  32. <!-- 日期日历控件 -->
  33. <form action="operatePerson.jsp" method="post">
  34. <input type="hidden" name="action" value="<%=isEdit ? "save" : "add"%>">
  35. <input type="hidden" name="id" value="<%=isEdit ? id : ""%>">
  36. <fieldset>
  37. <legend><%=isEdit ? "修改人员资料" : "新建人员资料"%></legend>
  38. <table align=center>
  39. <tr>
  40. <td>姓名</td>
  41. <td><input type="text" name="name" value="<%=isEdit ? name : ""%>" /></td>
  42. </tr>
  43. <tr>
  44. <td>英文名</td>
  45. <td><input type="text" name="englishName" value="<%=isEdit ? englishName : ""%>" /></td>
  46. </tr>
  47. <tr>
  48. <td>性别</td>
  49. <td><input type="radio" name="sex" value="男" id="sex_male"
  50. <%=isEdit && "".equals(sex) ? "checked" : ""%> />
  51. <label for="sex_male"></label>
  52. <input type="radio" name="sex" value="女" id="sex_female"
  53. <%=isEdit && "".equals(sex) ? "checked" : ""%> />
  54. <label for="sex_female"></label></td>
  55. </tr>
  56. <tr>
  57. <td>年龄</td>
  58. <td><input type="text" name="age" value="<%=isEdit ? age : ""%>" /></td>
  59. </tr>
  60. <tr>
  61. <td>生日</td>
  62. <td><input type="text" name="birthday" onfocus="setday(birthday)"
  63. value="<%=isEdit ? birthday : ""%>" /><img src="images/calendar.gif"
  64. onclick="setday(birthday);" /></td>
  65. </tr>
  66. <tr>
  67. <td>描述</td>
  68. <td><textarea name="description"><%=isEdit ? description : ""%></textarea></td>
  69. </tr>
  70. <tr>
  71. <td></td>
  72. <td><input type="submit" value="<%=isEdit ? "保存":"添加人员信息" %>" /></td>
  73. </tr>
  74. </table>
  75. </fieldset>
  76. </form>
  77. </body>
  78. </html>

                                                                              operatePerson.jsp

  1. <%@page import="java.text.SimpleDateFormat"%>
  2. <%@page import="java.sql.PreparedStatement"%>
  3. <%@page import="java.sql.ResultSet"%>
  4. <%@page import="java.sql.SQLException"%>
  5. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"
  6. contentType="text/html;charset=UTF-8"%>
  7. <%@ page import="java.sql.DriverManager"%>
  8. <%@ page import="java.sql.Connection"%>
  9. <%@ page import="java.sql.Statement"%>
  10. <%@ page import="java.sql.Date"%>
  11. <%@ page import="com.hedong.learn.Pagination" %>
  12. <%
  13. //获取各种数据
  14. request.setCharacterEncoding("UTF-8");
  15. String name = request.getParameter("name");
  16. String englishName = request.getParameter("englishName");
  17. String age = request.getParameter("age");
  18. String birthday = request.getParameter("birthday");
  19. String sex = request.getParameter("sex");
  20. String description = request.getParameter("description");
  21. String action = request.getParameter("action");
  22. //如果是添加操作
  23. if ("add".equals(action)) {
  24. Connection conn = null;
  25. Statement stmt = null;
  26. int result = 0;
  27. String sql = "INSERT INTO tb_person(name,english_name,age,sex,birthday,description)" + "values('" + name
  28. + "','" + englishName + "','" + age + "','" + sex + "','" + birthday + "','" + description
  29. + "')";
  30. try {
  31. conn=Pagination.getConnection();
  32. stmt = conn.createStatement();
  33. result = stmt.executeUpdate(sql);
  34. } catch (SQLException e) {
  35. out.println("执行SQL\"" + sql + "\"时发生异常:" + e.getMessage());
  36. return;
  37. } finally {
  38. if (stmt != null)
  39. stmt.close();
  40. if (conn != null)
  41. conn.close();
  42. }
  43. out.println("<html><style>body{font-size:12px;line-height:25px;}</style><body>");
  44. out.println(result + "条记录被添加到数据库中。");
  45. out.println("<a href='listPagedPerson.jsp'>返回人员列表</a>");
  46. out.println("<br/><br/>执行的SQL语句为:<br/>" + sql);
  47. return;
  48. }
  49. //如果是删除操作
  50. else if ("del".equals(action)) {
  51. String id=request.getParameter("id");
  52. String sql="delete from tb_person where id="+id;
  53. Connection conn = null;
  54. Statement stmt = null;
  55. try {
  56. conn=Pagination.getConnection();
  57. stmt = conn.createStatement();
  58. int result = stmt.executeUpdate(sql);
  59. out.println("<html><style>body{font-size:12px;line-height:25px;}</style><body>");
  60. out.println(result + "条记录被删除。");
  61. out.println("<a href='listPagedPerson.jsp'>返回人员列表</a>");
  62. out.println("<br/><br/>执行的SQL语句为:<br/>" + sql);
  63. } catch (SQLException e1) {
  64. out.println("执行SQL\"" + sql + "\"时发生异常:" + e1.getMessage());
  65. } finally {
  66. if (stmt != null)
  67. stmt.close();
  68. if (conn != null)
  69. conn.close();
  70. }
  71. }
  72. //如果是修改
  73. else if ("edit".equals(action)) {
  74. String id = request.getParameter("id");
  75. String sql = "SELECT * FROM tb_person WHERE id =" + id;
  76. Connection conn = null;
  77. Statement stmt = null;
  78. ResultSet rs = null;
  79. try {
  80. conn=Pagination.getConnection();
  81. stmt = conn.createStatement();
  82. rs = stmt.executeQuery(sql);
  83. if (rs.next()) {
  84. request.setAttribute("id", rs.getString("id"));
  85. request.setAttribute("name", rs.getString("name"));
  86. request.setAttribute("englishName", rs.getString("english_name"));
  87. request.setAttribute("age", rs.getString("age"));
  88. request.setAttribute("sex", rs.getString("sex"));
  89. request.setAttribute("birthday", rs.getString("birthday"));
  90. request.setAttribute("description", rs.getString("description"));
  91. request.setAttribute("action", action);
  92. request.getRequestDispatcher("/addPerson.jsp").forward(request, response);
  93. } else {
  94. out.println("没有找到id为" + id + "的记录。");
  95. }
  96. } catch (SQLException e2) {
  97. out.println("执行SQL\"" + sql + "\"时发生异常:" + e2.getMessage());
  98. e2.printStackTrace();
  99. } finally {
  100. if (rs != null)
  101. rs.close();
  102. if (stmt != null)
  103. stmt.close();
  104. if (conn != null)
  105. conn.close();
  106. }
  107. }
  108. //如果是保存操作
  109. else if ("save".equals(action)) {
  110. String id = request.getParameter("id");
  111. String sql = "UPDATE tb_person SET name=?,english_name=?,sex=?,age=?,birthday=?,description=? WHERE id=?";
  112. Connection conn = null;
  113. //用PreparedStatement,sql中可含有参数
  114. PreparedStatement preStmt = null;
  115. try {
  116. conn=Pagination.getConnection();
  117. SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
  118. Date d = new Date(f.parse(birthday).getTime());
  119. preStmt = conn.prepareStatement(sql);
  120. preStmt.setString(1, name);
  121. preStmt.setString(2, englishName);
  122. preStmt.setString(3, sex);
  123. preStmt.setInt(4, Integer.parseInt(age));
  124. preStmt.setDate(5, d);
  125. preStmt.setString(6, description);
  126. preStmt.setInt(7, Integer.parseInt(id));
  127. int result = preStmt.executeUpdate();//此时括号中无需填写sql
  128. out.println("<html><style>body{font-size:12px;line-height:25px;}</style><body>");
  129. if (result == 0)
  130. out.println("影响数目为0,修改失败。");
  131. else
  132. out.println(result + "条记录被修改。");
  133. out.println("<a href='listPagedPerson.jsp'>返回人员列表</a>");
  134. out.println("<br/><br/>执行的SQL语句为:<br/>" + sql);
  135. } catch (SQLException e3) {
  136. out.println("执行SQL\"" + sql + "\"时发生异常:" + e3.getMessage());
  137. e3.printStackTrace();
  138. } finally {
  139. if (preStmt != null)
  140. preStmt.close();
  141. if (conn != null)
  142. conn.close();
  143. }
  144. }
  145. %>

下面是运行后的结果

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/575421
推荐阅读
相关标签
  

闽ICP备14008679号