使用JDBC实现对数据的增删改查

为员工管理添加增加、删除和修改的功能,即在查询结果页面中提供删除、修改的操作链接,并实现在删除或修改后回到查询页面的效果。如下图所示:
使用JDBC实现对数据的增删改查_第1张图片

步骤
step1: 添加ListEmpServlet,添加删除链接、修改链接和添加链接
代码如下:

package web;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ListEmpServlet extends HttpServlet{
    protected void service(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException,IOException{
        //保证正确读取Post提交来的中文
        request.setCharacterEncoding("utf-8");
        //保证正确输出中文
        response.setContentType("text/html;charset=utf-8");
        //获取输出流对象,并输出信息
        PrintWriter out=response.getWriter();
        //获取表单提交的数据
        //String name= request.getParameter("name");
        //double salary = Double.valueOf(request.getParameter("salary"));
        //int age = Integer.valueOf(request.getParameter("age"));
        //将数据插入到数据库t_emp表中
        Connection conn = null;
        PreparedStatement stat=null;
        try {
            //1、加载MySQL的JDBC的驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2、取得连接的URL,能访问MySQL数据库的用户名和密码
            String url="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8";
            String username = "root";
            String password = "123456"; 
            //3、创建与MySQL数据库的连接类的实例
            conn=DriverManager.getConnection(url,username,password);
            stat=conn.prepareStatement("select * from t_emp");
            ResultSet rs = stat.executeQuery();
            //4、输出表格之前的页面标记
            out.println("");
            out.println("");
            out.println("");
            out.println("+
                         "cellspacing='0' width='600px'");out.println("");  //定义表格标题out.println(""+
                           "");
            //3、遍历结果集,以表格形式输出数据
            while(rs.next()){
                int id=rs.getInt("id");
                String name=rs.getString("name");
                double salary=rs.getDouble("salary");
                int age=rs.getInt("age");out.println("");out.println("");out.println("");out.println("");out.println("");out.println("");out.println("");
            }
            out.println("
员工信息列表
编号姓名薪水年龄 操作
"+id+" "+name+" "+salary+" "+age+" + "οnclick=\"return confirm('是否确定删除"+name+"');\">删除"); out.println("修改
"
); out.println(">>添加员工信息"); out.println(""); } catch (Exception e) { e.printStackTrace(); out.print("系统繁忙,稍后重试"); }finally{ if(stat!=null){ try { stat.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }

Step2: 新建DeleteEmpServlet类,处理删除动作
获取请求参数值id,构建删除语句并执行
代码如下:

package web;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class DeleteEmpServlet extends HttpServlet{
    private static final long serialVersionUID = 1L;

    protected void service(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException,IOException{
        //保证正确读取Post提交来的中文
        request.setCharacterEncoding("utf-8");
        //保证正确输出中文
        response.setContentType("text/html;charset=utf-8");
        //获取输出流对象,并输出信息
        PrintWriter out=response.getWriter();
        //获取删除的编号
        int id =Integer.parseInt(request.getParameter("id"));
        //连接数据库,执行删除操作
        Connection conn = null;
        PreparedStatement stmt=null;
        try {
            //1、加载MySQL的JDBC的驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2、取得连接的URL,能访问MySQL数据库的用户名和密码
            String url="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8";
            String username = "root";
            String password = "123456"; 
            //3、创建与MySQL数据库的连接类的实例
            conn=DriverManager.getConnection(url,username,password);
            stmt=conn.prepareStatement("delete from t_emp where id=?");//删除的sql语句
            stmt.setInt(1, id);
            stmt.executeUpdate();// 用于执行 INSERT、UPDATE 或 DELETE 语句以及 SQL DDL(数据定义语言)语句,例如 CREATE TABLE 和 DROP TABLE
            response.sendRedirect("list");  //重定向到查询页面
        } catch (Exception e) {
            e.printStackTrace();
            out.print("系统繁忙,稍后重试");
        }finally{
            if(stmt!=null){
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }

            }
        }

    }
}

Step3 : 新建LoadEmpServlet.java文件
获取请求参数值id,查询数据并构建表单显示数据
代码如下:

package web;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class LoadEmpServlet extends HttpServlet{
    protected void service(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException,IOException{
        //保证正确读取Post提交来的中文
        request.setCharacterEncoding("utf-8");
        //保证正确输出中文
        response.setContentType("text/html;charset=utf-8");
        //获取输出流对象,并输出信息
        PrintWriter out=response.getWriter();
        //获取请求参数值id
        int id = Integer.parseInt(request.getParameter("id"));
        //根据ID查询数据库获取员工信息
        Connection conn = null;
        PreparedStatement stmt=null;
        ResultSet rs=null;
        try {
            //1、加载MySQL的JDBC的驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2、取得连接的URL,能访问MySQL数据库的用户名和密码
            String url="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8";
            String username = "root";
            String password = "123456"; 
            //3、创建与MySQL数据库的连接类的实例
            conn=DriverManager.getConnection(url,username,password);
            stmt=conn.prepareStatement("select * from t_emp where id=?");
            stmt.setInt(1, id);
            rs=stmt.executeQuery();
            out.println("");
            if(rs.next()){
                String name=rs.getString("name");
                double salary=rs.getDouble("salary");
                int age=rs.getInt("age");
                out.println("
");//输出表单 out.println("编号:"+ id + "
"
); out.println("
"
); out.println("姓名:
"
); out.println("薪水:
"
); out.println("年龄:
"
); out.println(""); out.println(""
); out.println(""); } } catch (Exception e) { e.printStackTrace(); out.print("系统繁忙,稍后重试"); }finally{ if(stmt!=null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }

Step4: 新建ModifyEmpServlet.java文件
修改数据表中的数据
代码如下:

package web;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class ModifyEmpServlet extends HttpServlet{
    protected void service(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException,IOException{
        //保证正确读取Post提交来的中文
        request.setCharacterEncoding("utf-8");
        //保证正确输出中文
        response.setContentType("text/html;charset=utf-8");
        //获取输出流对象,并输出信息
        PrintWriter out=response.getWriter();
        //1、获取请求参数值
        int id=Integer.parseInt(request.getParameter("id"));
        String name= request.getParameter("name");
        double salary = Double.valueOf(request.getParameter("salary"));
        int age = Integer.valueOf(request.getParameter("age"));
        //2、数据库数据更新
        Connection conn = null;
        PreparedStatement stmt=null;
        try {
            //1、加载MySQL的JDBC的驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2、取得连接的URL,能访问MySQL数据库的用户名和密码
            String url="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8";
            String username = "root";
            String password = "123456"; 
            //3、创建与MySQL数据库的连接类的实例
            conn=DriverManager.getConnection(url,username,password);
            stmt=conn.prepareStatement("update t_emp set name=?,"+
                    "salary=?,age=? where id=?"); //数据更新SQL
            stmt.setString(1, name);
            stmt.setDouble(2, salary);
            stmt.setInt(3, age);
            stmt.setInt(4, id);
            stmt.executeUpdate();
            response.sendRedirect("list");//从定向到查询界面
        } catch (Exception e) {
            e.printStackTrace();
            out.print("系统繁忙,稍后重试");
        }finally{
            if(stmt!=null){
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }

            }
        }

    }
}

Step5: 新建AddEmpServlet.java文件
添加数据:
代码如下:

package web;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AddEmpServlet extends HttpServlet
{
    protected void service(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
    {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();

        //读取请求参数值
        String name = request.getParameter("name");
        double salary = Double.parseDouble(request.getParameter("salary"));
        int age = Integer.parseInt(request.getParameter("age"));

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //JDBC
        Connection conn = null;
        PreparedStatement stat = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            //2、取得连接的URL,能访问MySQL数据库的用户名和密码
            String url="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8";
            String username = "root";
            String password = "123456"; 
            //3、创建与MySQL数据库的连接类的实例
            conn=DriverManager.getConnection(url,username,password);

            stat = conn.prepareStatement("INSERT INTO t_emp(name,salary,age) VALUES(?,?,?)");
            stat.setString(1, name);
            stat.setDouble(2, salary);
            stat.setInt(3, age);
            stat.executeUpdate();
//          out.println("添加员工成功");
//          out.println("查看所有员工");
            //重定向到员工列表
            response.sendRedirect("list");
            System.out.println("重定向之后的代码");
        } catch (Exception e) {
            e.printStackTrace();
            /*
             * 判断异常是否能够恢复,如果不能够恢复
             * (比如,数据库服务暂停,网络中断等等,一般称之为系统异常),提示用户稍后重试即可。
             * 如果能够恢复(应用异常),要立即恢复。
             */
            out.println("系统繁忙,稍后重试");
        }finally{
            if(stat!=null){
                try{
                    stat.close();
                }catch(SQLException e){
                    e.printStackTrace();
                }
            }
            if(conn!=null){
                try{
                    conn.close();
                }catch(SQLException e){
                    e.printStackTrace();
                }
            }
        }
    }
}

Step6: 新建一个addEmp.jsp文件,实现添加员工信息操作
代码如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


<html>
  <head>
    <base href="<%=basePath%>">

    <title>Servlet programtitle>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
    
  head>

  <body>
    <form action="add" method="post"> 
        <fieldset>
            <legend>添加员工legend>
            姓名:<input name="name"/><br>
            薪水:<input name="salary"/><br>
            年龄:<input name="age"/><br>
            <input type="submit" value="添加">
        fieldset>
    form>
  body>
html>

Step6: 修改web.xml文件实现配置


<web-app version="3.0" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name>display-name> 
  <welcome-file-list>
    <welcome-file>addEmp.jspwelcome-file>
  welcome-file-list>
 
  <servlet>
    <servlet-name>addEmpServletservlet-name>
    <servlet-class>web.AddEmpServletservlet-class>
  servlet>
  
  <servlet>
    <servlet-name>deleteEmpServletservlet-name>
    <servlet-class>web.DeleteEmpServletservlet-class>
  servlet>
  
  <servlet>
    <servlet-name>loadEmpServletservlet-name>
    <servlet-class>web.LoadEmpServletservlet-class>
  servlet>
   
  <servlet>
    <servlet-name>modifyEmpServletservlet-name>
    <servlet-class>web.ModifyEmpServletservlet-class>
  servlet>
  
  <servlet>
    <servlet-name>listEmpServletservlet-name>
    <servlet-class>web.ListEmpServletservlet-class>
  servlet>
  <servlet-mapping>
    <servlet-name>addEmpServletservlet-name>
    <url-pattern>/addurl-pattern>  
  servlet-mapping>
  <servlet-mapping>
    <servlet-name>deleteEmpServletservlet-name>
    <url-pattern>/deleteurl-pattern>  
  servlet-mapping>
  <servlet-mapping>
    <servlet-name>loadEmpServletservlet-name>
    <url-pattern>/loadurl-pattern>  
  servlet-mapping>
  <servlet-mapping>
    <servlet-name>modifyEmpServletservlet-name>
    <url-pattern>/modifyurl-pattern>  
  servlet-mapping>
  <servlet-mapping>
    <servlet-name>listEmpServletservlet-name>
    <url-pattern>/listurl-pattern>  
  servlet-mapping>
web-app>

Step7 :加载到Tomcat服务器中,在浏览器运行
页面见第一个图。

附上表结构sql:


-- ----------------------------
-- Table structure for t_emp
-- ----------------------------
DROP TABLE IF EXISTS `t_emp`;
CREATE TABLE `t_emp` (
  `id` int(4) NOT NULL AUTO_INCREMENT,
  `name` varchar(8) NOT NULL,
  `salary` float(8,2) DEFAULT NULL,
  `age` int(2) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;

感谢 u014586688 指出问题,现已更改,程序测试成功。
AddEmpServlet.java已在上面添加。
另外,对web.xml文件做一个修改,修改位置如下:

file-list>
    file>addEmp.jspfile>
  file-list>

注意:运行此例子需要加载mysql的jar包,
我使用的是:mysql-connector-java-5.1.7-bin.jar

这样,一个简单的增删改查操作就完成了。
如果发现不妥或疑问之处,麻烦提出。这段时间正在学习这方面的知识,欢迎交流。

你可能感兴趣的:(Java)