⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 preparedstatementservlet.java

📁 JAVA编程百例书中各章节的所有例子的源代码,包括套接字编程
💻 JAVA
字号:
package ch03.section05;

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

import ch03.section03.*;

public class PreparedStatementServlet
    extends HttpServlet {
  String sqlStr;
  static final private String CONTENT_TYPE = "text/html; charset=gb2312";
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws
      ServletException, IOException {
    response.setContentType(CONTENT_TYPE);
    PrintWriter out = response.getWriter();
    HttpSession session = request.getSession();
    //利用数据库连接池新建一个连接
    DBConnectionManager connMgr = DBConnectionManager.getInstance();
    Connection conn = null;
    conn = connMgr.getConnection("access");
    try {
      String studentName = request.getParameter("studentName");
      //防止乱码
      studentName = new String(studentName.getBytes("8859_1"), "GB2312");
      String studentAge = request.getParameter("studentAge");
      String studentGrade = request.getParameter("studentGrade");
      String studentID = (String) session.getAttribute("studentID");
      //sql语句
      sqlStr = "update ch03section04 " +
          "set studentName = ? ,studentAge = ?,studentGrade = ? where studentID = ? ";
      if (conn == null) {
        System.out.println("数据库连接不成功!");
      }
      else {
        //新建PreparedStatement对象
        PreparedStatement updateOp = conn.prepareStatement(sqlStr);
        updateOp.setString(1, studentName);
        updateOp.setInt(2, Integer.parseInt(studentAge));
        updateOp.setFloat(3, Float.parseFloat(studentGrade));
        updateOp.setInt(4, Integer.parseInt(studentID));
        updateOp.executeUpdate();
        //将更新的后的数据显示给用户
        response.sendRedirect("../servlet/ch03.section05.DBSelectServlet");
        updateOp.close();
        return;
      }
    }
    catch (Exception ex) {
      System.out.println(ex.toString());
    }
    finally {
      //释放数据库连接
      connMgr.freeConnection("access", conn);
    }
  }

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

  public void destroy() {
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -