码迷,mamicode.com
首页 > 数据库 > 详细

java ee 在数据库中执行增删改查

时间:2016-07-08 13:25:03      阅读:618      评论:0      收藏:0      [点我收藏+]

标签:

1.先建一个主页面里面包含着添加方法

<%@page import="java.text.SimpleDateFormat"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ page import="java.sql.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>学生信息</title>
</head>
<body>
学生信息列表
<br>
<%
try
{
//1.连接数据库
// 1)加载驱动

Class.forName("oracle.jdbc.driver.OracleDriver");
// 2)得到连接
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "test1", "duibuqi19950220");

//2.读取
Statement st=conn.createStatement();


ResultSet rs=st.executeQuery("select * from STUDENT");
//3.输出结果集
if(rs!=null)
{
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd ");
    
    while(rs.next())
    {
        
        out.print("SNO="+rs.getString("SNO")+" ");
        out.print("name="+rs.getString("sname")+" ");
        out.print("ssex="+rs.getString("ssex")+" ");
        out.print("sbirthday="+        
                (rs.getDate("sbirthday")==null?rs.getDate("sbirthday"):sdf.format(rs.getDate("sbirthday")))+" ");
        out.print("class="+rs.getString("class"));
        out.print("<a href=‘update.jsp?SNO="+rs.getString("SNO")+"‘>【修改】</a><a href=‘DeleteStudent?SNO="+rs.getString("SNO")+"‘>【删除】</a><br>");
        
        
    }
    rs.close();
}
//4.释放资源
    st.close();
    conn.close();
  
    
}
catch(Exception e)
{
   e.printStackTrace();    
}
%>

添加学生信息<br>
<form action="SaveStudent" method="post">
学号:<input type="text" name="sno"><br>
名称:<input type="text" name="sname"><br>
性别:<input type="text" name="ssex"><br>
生日:<input type="text" name="sbirthday"><br>
班级:<input type="text" name="class"><br>
<input type="submit" value="保存">
</form>



</body>
</html>

2.建设修改和删除的界面

<%@page import="java.text.SimpleDateFormat"%>
<%@ page import="java.sql.*" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>修改学生信息</title>
</head>
<body>
<%

//接收主键,从数据库读取最新数据再进行修改
try{
String sno=request.getParameter("SNO");
String sname=null;
String ssex=null;
String sbirthday=null;
String sclass=null;
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
if(sno!=null && sno.trim().length()>0)
{
    //读取最新数据
    try {
                Class.forName("oracle.jdbc.driver.OracleDriver");
            
            // 2)得到连接
            Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "test1", "duibuqi19950220");


            PreparedStatement p=conn.prepareStatement(
                    "select * from STUDENT where SNO=?");        
            
            p.setString(1, sno);
            
            ResultSet rs=p.executeQuery();
            if(rs!=null&&rs.next())
            {
                sname=rs.getString("sname");
                ssex=rs.getString("ssex");
                
            
                sbirthday=sdf.format(rs.getDate("sbirthday"));
                sclass=rs.getString("class");
                
                rs.close();
            }
            else
            {
                out.print("未查询到数据");
            }
        
            p.close();
            conn.close();
            
            
            
            } catch (Exception e) {
            
                e.printStackTrace();
                
            }
}
else
{
     out.print("请正确访问");    
}

%>


修改学生信息<br>
<form action="SaveStudent" method="post">
学号:<input type="text" name="sno" readonly="readonly" value="<%=sno %>"><br>
名称:<input type="text" name="sname" value="<%=sname %>"><br>
性别:<input type="text" name="ssex" value="<%=ssex %>"><br>
生日:<input type="text" name="sbirthday" value="<%=sbirthday==null?"":sbirthday %>"><br>
班级:<input type="text" name="class" value="<%=sclass %>"><br>
<input type="hidden" name="isupdate" value="1">
<input type="submit" value="保存">



</form>
<%
}catch(Exception e)
{
    }
%>
</body>
</html>

3.加上过滤器Filter包含转码防止在网页中出现乱码

package com.hanqi.web;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;


public class MyFilter implements Filter {

  
    public MyFilter() {
        
    }

    public void destroy() {
    
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");        
        request.setCharacterEncoding("UTF-8");
       
        chain.doFilter(request, response);
    }

    
    public void init(FilterConfig fConfig) throws ServletException {
    }

}

4.删除Servlet类

package com.hanqi.web;
import java.sql.*;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class DeleteStudent
 */
public class DeleteStudent extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DeleteStudent() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String sno=request.getParameter("SNO");
        if(sno!=null&& sno.trim().length()!=0)                
        {
            try {
                Class.forName("oracle.jdbc.driver.OracleDriver");
            
            // 2)得到连接
            Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "test1", "duibuqi19950220");

            //2.删除数据
//            Statement st=conn.createStatement();
//            st.executeUpdate("");
            PreparedStatement pst=conn.prepareStatement(
                    "delete STUDENT where "+"SNO=?");
        
            pst.setString(1, sno);
            
            
            pst.executeUpdate();
            pst.close();
            conn.close();
            
            //4.跳转页面
            response.getWriter().write("删除成功");
            response.setHeader("refresh", "3;URL=index.jsp");
            } catch (Exception e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
                response.getWriter().write("删除失败");
                response.setHeader("refresh", "3;URL=index.jsp");
            }    
            
        }
        else
        {
            response.getWriter().write("请正确提交数据");
            response.setHeader("refresh", "3;URL=index.jsp");
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

5.Servlet包含插入和修改的方法

package com.hanqi.web;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class SaveStudent
 */
public class SaveStudent extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public SaveStudent() {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         //处理保存数据的请求
        //1.接收参数
        String sno=request.getParameter("sno");
        String sname=request.getParameter("sname");
        String ssex=request.getParameter("ssex");
        String sbirthday=request.getParameter("sbirthday");
        String sclass=request.getParameter("class");
        
        //是否更新
        String isupdate=request.getParameter("isupdate");
        //2.验证
        if(sno!=null&& sno.trim().length()!=0
                &&sname!=null&& sname.trim().length()!=0)
        {
            //3.保存
            try {
                Class.forName("oracle.jdbc.driver.OracleDriver");
            
            // 2)得到连接
            Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "test1", "duibuqi19950220");

            //2.插入数据
//            Statement sat=conn.createStatement();
//            st.executeUpdate("");
            
            //执行插入还是更新
            
            //插入
            PreparedStatement pst=conn.prepareStatement(
                    "insert into STUDENT (sname,ssex,sbirthday,class,sno)"+
                         "values(?,?,?,?,?)");
            if(isupdate!=null&& isupdate.equals("1"))
            {
                //更新
                pst = conn.prepareStatement(
                        "update STUDENT set sname=?,ssex=?,sbirthday=?,class=? where sno=?");
            }
            
                //插入
            
            
            //String 转成 Date
            //关于日期格式的类
            //可以进行日期转换
            SimpleDateFormat adf = new SimpleDateFormat("yyyy-MM-dd");
            java.util.Date bir= adf.parse(sbirthday);
            
            //使用 long 型的时间构造sql.Date
            Date sqlBir = new Date(bir.getTime());
            
            
            pst.setString(1, sname);
            pst.setString(2, ssex);
            pst.setDate(3, sqlBir);
            pst.setString(4, sclass);
            pst.setString(5, sno);
            
            pst.executeUpdate();
            
            
            
            pst.close();
            conn.close();
            
            //4.跳转页面
            response.getWriter().write("保存成功");
            response.setHeader("refresh", "3;URL=index.jsp");
            } catch (Exception e) {
                
                e.printStackTrace();
                response.getWriter().write("保存失败");
                response.setHeader("refresh", "3;URL=index.jsp");
            }
            
            
        }
        else
        {
            response.getWriter().write("请正确提交数据");
            response.setHeader("refresh", "3;URL=index.jsp");
        }
        
        
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        doGet(request, response);
    }

}
package com.hanqi.web;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class SaveStudent
 */
public class SaveStudent extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public SaveStudent() {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         //处理保存数据的请求
        //1.接收参数
        String sno=request.getParameter("sno");
        String sname=request.getParameter("sname");
        String ssex=request.getParameter("ssex");
        String sbirthday=request.getParameter("sbirthday");
        String sclass=request.getParameter("class");
        
        //是否更新
        String isupdate=request.getParameter("isupdate");
        //2.验证
        if(sno!=null&& sno.trim().length()!=0
                &&sname!=null&& sname.trim().length()!=0)
        {
            //3.保存
            try {
                Class.forName("oracle.jdbc.driver.OracleDriver");
            
            // 2)得到连接
            Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "test1", "duibuqi19950220");

            //2.插入数据
//            Statement sat=conn.createStatement();
//            st.executeUpdate("");
            
            //执行插入还是更新
            
            //插入
            PreparedStatement pst=conn.prepareStatement(
                    "insert into STUDENT (sname,ssex,sbirthday,class,sno)"+
                         "values(?,?,?,?,?)");
            if(isupdate!=null&& isupdate.equals("1"))
            {
                //更新
                pst = conn.prepareStatement(
                        "update STUDENT set sname=?,ssex=?,sbirthday=?,class=? where sno=?");
            }
            
                //插入
            
            
            //String 转成 Date
            //关于日期格式的类
            //可以进行日期转换
            SimpleDateFormat adf = new SimpleDateFormat("yyyy-MM-dd");
            java.util.Date bir= adf.parse(sbirthday);
            
            //使用 long 型的时间构造sql.Date
            Date sqlBir = new Date(bir.getTime());
            
            
            pst.setString(1, sname);
            pst.setString(2, ssex);
            pst.setDate(3, sqlBir);
            pst.setString(4, sclass);
            pst.setString(5, sno);
            
            pst.executeUpdate();
            
            
            
            pst.close();
            conn.close();
            
            //4.跳转页面
            response.getWriter().write("保存成功");
            response.setHeader("refresh", "3;URL=index.jsp");
            } catch (Exception e) {
                
                e.printStackTrace();
                response.getWriter().write("保存失败");
                response.setHeader("refresh", "3;URL=index.jsp");
            }
            
            
        }
        else
        {
            response.getWriter().write("请正确提交数据");
            response.setHeader("refresh", "3;URL=index.jsp");
        }
        
        
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        doGet(request, response);
    }

}

 

java ee 在数据库中执行增删改查

标签:

原文地址:http://www.cnblogs.com/zzyu/p/5652942.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!