赞
踩
数据库的增、删、改、查是非常重要的操作,只要程序是关于数据库的操作,无论程序大小,归根结底都是这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
- <%@page import="org.apache.jasper.tagplugins.jstl.core.Param"%>
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"
- contentType="text/html;charset=UTF-8"%>
- <%@ page import="java.sql.Connection"%>
- <%@ page import="java.sql.ResultSet"%>
- <%@ page import="java.sql.Statement"%>
- <%@ page import="java.sql.DriverManager"%>
- <jsp:directive.page import="java.sql.Date" />
- <jsp:directive.page import="java.sql.Timestamp" />
- <jsp:directive.page import="java.sql.SQLException" />
- <jsp:directive.page import="java.sql.PreparedStatement" />
- <jsp:directive.page import="com.hedong.learn.Pagination" />
-
- <style>a{text-decoration:none}</style> <%--去掉页面超链接的注释 --%>
-
- <form action="listPagedPerson.jsp" method=get>
- <input type="hidden" name="action" value="search"> <%--执行查询操作 --%>
- <table align="center">
- <tr>
- <td>姓名</td>
- <td><input type="text" name='name' value="${param.name}" ></td>
- <td><input type="submit" value="查询"></td>
- </tr>
- </table>
- </form>
-
-
-
- <%
- final int pageSize = 5; //每页10条数据
- int pageNum = 1; //当前页数,默认从第一页开始
- int pageCount = 1; //总页数
- int recordCount = 0; //总共有多少条记录
- String action=request.getParameter("action");
-
- try {
- pageNum = Integer.parseInt(request.getParameter("pageNum"));//取当前页数
- } catch (Exception e) {
- }
-
- String sql = null;
- Connection conn = null;
- Statement stmt = null;
- ResultSet rs = null;
-
- try {
- if(!"search".equals(action))
- {
-
- conn=Pagination.getConnection();
- stmt = conn.createStatement();
- sql = "SELECT count(*) FROM tb_person "; //查询记录总数的sql语句
- rs = stmt.executeQuery(sql);
- if (rs.next()) {
- recordCount = rs.getInt(1);//获得记录总数
- }
-
- pageCount = (recordCount + pageSize - 1) / pageSize;//计算总页数
- int startRecord = (pageNum - 1) * pageSize; //计算本页记录从stratRecord开始
-
- sql = "Select * from tb_person LIMIT "+startRecord+","+pageSize;//此sql语句将记录进行分页
- rs = stmt.executeQuery(sql);
- }
- else if("search".equals(action))
- {
- String name=request.getParameter("name");//获得要查询的人的名字
- conn=Pagination.getConnection();
- sql="SELECT * FROM tb_person WHERE name='"+name+"'";
- stmt = conn.createStatement();
- rs = stmt.executeQuery(sql);
- }
-
- %>
- <form action="operatePerson.jsp" method=get>
- <table bgcolor="#CCCCCC" cellspacing=1 cellpadding=5 width=100%>
- <tr bgcolor=#DDDDDD>
- <th>序号</th>
- <th>姓名</th>
- <th>英文名</th>
- <th>性别</th>
- <th>年龄</th>
- <th>生日</th>
- <th>备注</th>
- <th>操作</th>
- </tr>
- <%
- int count=1;
- while (rs.next()) {
- //获得表中各数据
- int id = rs.getInt("id");
- int age = rs.getInt("age");
- String name = rs.getString("name");
- String englishName = rs.getString("english_name");
- String sex = rs.getString("sex");
- String description = rs.getString("description");
- Date birthday = rs.getDate("birthday");
- //将数据进行写出
- out.println("<tr bgcolor=#FFFFFF>");
- out.println("<td>" + count + "</td>");
- out.println("<td>" + name + "</td>");
- out.println("<td>" + englishName + "</td>");
- out.println("<td>" + sex + "</td>");
- out.println("<td>" + age + "</td>");
- out.println("<td>" + birthday + "</td>");
- out.println("<td>" + description + "</td>");
- out.println("<td>");
- out.println("<a href='operatePerson.jsp?action=del&id=" + id
- + "' onclick='return confirm(\"确定删除记录?\");'>删除</a>");
- out.println("<a href='operatePerson.jsp?action=edit&id=" + id + "'>修改</a>");
- out.println("</td");
- out.println("</tr>");
- count++;
- }
- %>
- <tr>
- <td colspan="2" align="left"><a href="addPerson.jsp">新建人员资料</a> <!-- 转到添加人员的页面 --></td>
- <td colspan="6" align="right"><%=Pagination.getPagination(pageNum, pageCount, recordCount, request.getRequestURI())%></td>
- </tr>
- </table>
- </form>
-
- <%
- } catch (SQLException e) {
- out.println("执行SQL:" + sql + "时发生异常:" + e.getMessage());
- e.printStackTrace();
- } finally {
- if (rs != null)
- rs.close();
- if (stmt != null)
- stmt.close();
- if (conn != null)
- conn.close();
- }
- %>
- </body>
- </html>
-
-
addPerson.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"
- contentType="text/html;charset=UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
- + path + "/";
- %>
-
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <%
- String action = (String) request.getAttribute("action");
- String id = (String) request.getAttribute("id");
- String name = (String) request.getAttribute("name");
- String englishName = (String) request.getAttribute("englishName");
- String age = (String) request.getAttribute("age");
- String sex = (String) request.getAttribute("sex");
- String birthday = (String) request.getAttribute("birthday");
- String description = (String) request.getAttribute("description");
-
- boolean isEdit = "edit".equals(action);//判断是修改还是添加操作
- %>
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
- <title><%=isEdit ? "修改人员资料" : "新建人员资料"%></title>
- <style type="text/css">
- body, td {
- font-size: 12px;
- }
- </style>
- </head>
- <body>
- <script type="text/javascript" src="js/calendar.js"></script>
- <!-- 日期日历控件 -->
- <form action="operatePerson.jsp" method="post">
- <input type="hidden" name="action" value="<%=isEdit ? "save" : "add"%>">
- <input type="hidden" name="id" value="<%=isEdit ? id : ""%>">
- <fieldset>
- <legend><%=isEdit ? "修改人员资料" : "新建人员资料"%></legend>
- <table align=center>
- <tr>
- <td>姓名</td>
- <td><input type="text" name="name" value="<%=isEdit ? name : ""%>" /></td>
- </tr>
- <tr>
- <td>英文名</td>
- <td><input type="text" name="englishName" value="<%=isEdit ? englishName : ""%>" /></td>
- </tr>
- <tr>
- <td>性别</td>
- <td><input type="radio" name="sex" value="男" id="sex_male"
- <%=isEdit && "男".equals(sex) ? "checked" : ""%> />
- <label for="sex_male">男</label>
- <input type="radio" name="sex" value="女" id="sex_female"
- <%=isEdit && "女".equals(sex) ? "checked" : ""%> />
- <label for="sex_female">女</label></td>
- </tr>
- <tr>
- <td>年龄</td>
- <td><input type="text" name="age" value="<%=isEdit ? age : ""%>" /></td>
- </tr>
- <tr>
- <td>生日</td>
- <td><input type="text" name="birthday" onfocus="setday(birthday)"
- value="<%=isEdit ? birthday : ""%>" /><img src="images/calendar.gif"
- onclick="setday(birthday);" /></td>
- </tr>
- <tr>
- <td>描述</td>
- <td><textarea name="description"><%=isEdit ? description : ""%></textarea></td>
- </tr>
- <tr>
- <td></td>
- <td><input type="submit" value="<%=isEdit ? "保存":"添加人员信息" %>" /></td>
- </tr>
- </table>
- </fieldset>
- </form>
- </body>
- </html>
-
operatePerson.jsp
- <%@page import="java.text.SimpleDateFormat"%>
- <%@page import="java.sql.PreparedStatement"%>
- <%@page import="java.sql.ResultSet"%>
- <%@page import="java.sql.SQLException"%>
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"
- contentType="text/html;charset=UTF-8"%>
- <%@ page import="java.sql.DriverManager"%>
- <%@ page import="java.sql.Connection"%>
- <%@ page import="java.sql.Statement"%>
- <%@ page import="java.sql.Date"%>
- <%@ page import="com.hedong.learn.Pagination" %>
-
- <%
- //获取各种数据
- request.setCharacterEncoding("UTF-8");
- String name = request.getParameter("name");
- String englishName = request.getParameter("englishName");
- String age = request.getParameter("age");
- String birthday = request.getParameter("birthday");
- String sex = request.getParameter("sex");
- String description = request.getParameter("description");
- String action = request.getParameter("action");
- //如果是添加操作
- if ("add".equals(action)) {
- Connection conn = null;
- Statement stmt = null;
- int result = 0;
-
- String sql = "INSERT INTO tb_person(name,english_name,age,sex,birthday,description)" + "values('" + name
- + "','" + englishName + "','" + age + "','" + sex + "','" + birthday + "','" + description
- + "')";
-
- try {
- conn=Pagination.getConnection();
- stmt = conn.createStatement();
- result = stmt.executeUpdate(sql);
-
- } catch (SQLException e) {
- out.println("执行SQL\"" + sql + "\"时发生异常:" + e.getMessage());
- return;
-
- } finally {
-
- if (stmt != null)
- stmt.close();
- if (conn != null)
- conn.close();
- }
-
- out.println("<html><style>body{font-size:12px;line-height:25px;}</style><body>");
- out.println(result + "条记录被添加到数据库中。");
- out.println("<a href='listPagedPerson.jsp'>返回人员列表</a>");
- out.println("<br/><br/>执行的SQL语句为:<br/>" + sql);
- return;
- }
- //如果是删除操作
- else if ("del".equals(action)) {
- String id=request.getParameter("id");
- String sql="delete from tb_person where id="+id;
-
- Connection conn = null;
- Statement stmt = null;
- try {
- conn=Pagination.getConnection();
- stmt = conn.createStatement();
- int result = stmt.executeUpdate(sql);
-
- out.println("<html><style>body{font-size:12px;line-height:25px;}</style><body>");
- out.println(result + "条记录被删除。");
- out.println("<a href='listPagedPerson.jsp'>返回人员列表</a>");
- out.println("<br/><br/>执行的SQL语句为:<br/>" + sql);
-
- } catch (SQLException e1) {
- out.println("执行SQL\"" + sql + "\"时发生异常:" + e1.getMessage());
- } finally {
- if (stmt != null)
- stmt.close();
- if (conn != null)
- conn.close();
- }
-
- }
- //如果是修改
- else if ("edit".equals(action)) {
- String id = request.getParameter("id");
- String sql = "SELECT * FROM tb_person WHERE id =" + id;
-
- Connection conn = null;
- Statement stmt = null;
- ResultSet rs = null;
-
- try {
- conn=Pagination.getConnection();
- stmt = conn.createStatement();
- rs = stmt.executeQuery(sql);
-
- if (rs.next()) {
- request.setAttribute("id", rs.getString("id"));
- request.setAttribute("name", rs.getString("name"));
- request.setAttribute("englishName", rs.getString("english_name"));
- request.setAttribute("age", rs.getString("age"));
- request.setAttribute("sex", rs.getString("sex"));
- request.setAttribute("birthday", rs.getString("birthday"));
- request.setAttribute("description", rs.getString("description"));
- request.setAttribute("action", action);
-
- request.getRequestDispatcher("/addPerson.jsp").forward(request, response);
-
- } else {
- out.println("没有找到id为" + id + "的记录。");
- }
-
- } catch (SQLException e2) {
- out.println("执行SQL\"" + sql + "\"时发生异常:" + e2.getMessage());
- e2.printStackTrace();
- } finally {
- if (rs != null)
- rs.close();
- if (stmt != null)
- stmt.close();
- if (conn != null)
- conn.close();
- }
-
- }
- //如果是保存操作
- else if ("save".equals(action)) {
- String id = request.getParameter("id");
- String sql = "UPDATE tb_person SET name=?,english_name=?,sex=?,age=?,birthday=?,description=? WHERE id=?";
-
- Connection conn = null;
- //用PreparedStatement,sql中可含有参数
- PreparedStatement preStmt = null;
-
- try {
- conn=Pagination.getConnection();
-
- SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
- Date d = new Date(f.parse(birthday).getTime());
-
- preStmt = conn.prepareStatement(sql);
- preStmt.setString(1, name);
- preStmt.setString(2, englishName);
- preStmt.setString(3, sex);
- preStmt.setInt(4, Integer.parseInt(age));
- preStmt.setDate(5, d);
- preStmt.setString(6, description);
- preStmt.setInt(7, Integer.parseInt(id));
-
- int result = preStmt.executeUpdate();//此时括号中无需填写sql
-
- out.println("<html><style>body{font-size:12px;line-height:25px;}</style><body>");
-
- if (result == 0)
- out.println("影响数目为0,修改失败。");
- else
- out.println(result + "条记录被修改。");
-
- out.println("<a href='listPagedPerson.jsp'>返回人员列表</a>");
- out.println("<br/><br/>执行的SQL语句为:<br/>" + sql);
-
- } catch (SQLException e3) {
- out.println("执行SQL\"" + sql + "\"时发生异常:" + e3.getMessage());
- e3.printStackTrace();
- } finally {
- if (preStmt != null)
- preStmt.close();
- if (conn != null)
- conn.close();
- }
- }
- %>
下面是运行后的结果
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。