DOC

Beginner Using Servlets to display, insert and update records in database

By Julie Morgan,2014-09-16 13:06
13 views 0
Beginner Using Servlets to display, insert and update records in database

    Beginner Using Servlets to display, insert and update records in

    database.(3)

作者;spring.z

email: spring.z@elong.com

日期;2001-7-3 9:11:12

Updating records in the Database with Java Servlets.

Overview :

    This article is next in the series of articles about selecting, inserting, updating and deleting records from the database using JDBC. In this article we will learn how to update records in the database. If you have followed my earlier article about 'Inserting

    records in the Database' then this article is not going to be difficult at all. 90% of the code will be same. So if you haven't read that article then I will suggest that you go through that article before starting this one as quite a few important things

    have been explained in detail there.

How to Update Records ?

    To update records in the database we will be using the same PreparedStatement class we used before for inserting records. Although we can update records using the Statement class, the

    update operation is less efficient and not optimized at all. PreparedStatement fills that gap and lets us build SQL queries which are compiled and thus more efficient.

PreparedStatement :

This class like other JDBC classes we have been discussing is

    present in the java.sql package. This is how you get handle on a PreparedStatement object :

    String sql = "UPDATE Names SET first_name=?, last_name=? WHERE ID=?";

// con is Connection object

PreparedStatement ps = con.prepareStatement(sql);

    Connection.prepareStatement() returns a reference to the PreparedStatement object. The only argument to the

    Connection.prepareStatement() method is an SQL statement containing optional '?' ( question mark ).

You should put '?' marks in the statement where you are going to

    put or change the values, for example in my example above I placed '?' marks at three places where I will put different values depending on the values entered by the user.

So how to set the values of '?' parameters. You set the values by

    using a setXxx() methods of PreparedStatement class. setXxx() are over 25 methods whose syntax is setObject(int paramIndex, Object

    o) where paramIndex is the number of '?' mark from left to right in the SQL statement. For example we will use setString(1, value1)

    and setString(2, value2) methods to set the value of both parameters to two different values. And setInt(3, value3) to set the value of third '?' mark to value3.

     ps.setString(1, "First Name");

     ps.setString(2, "Last Name");

     ps.setId(3, 1);

     ps.executeUpdate();

    Once the parameters are set in the PreparedStatement object, we execute the query using PreparedStatement.executeUpdate() method. You should use PreparedStatement.executeUpdate() for update,

    UPDATE and DELETE SQL queries and PreparedStatement.executeQuery() for any SQL statement that returns records.

    On the next page we make use of PreparedStatement object to develop a user Form page in which a user can update his first and

    last names and then when he presses the 'submit' button the existing record is updateed in the database using the methods we just discussed.

UpdateServlet :

Create a new UpdateServlet.java file in the /APP_NAME/WEB-

    INF/classes/com/stardeveloper/servlets/db/ folder. Note /APP_NAME/

    is the path of your application within your application server, in Tomcat 4.0 /APP_NAME/ will be /CATALINA_HOME/webapps/star/ where 'star' is the name of the application.

Copy and paste the following code into the UpdateServlet.java

    file :

package com.stardeveloper.servlets.db;

import java.sql.*;

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

    public class UpdateServlet extends HttpServlet {

     public void doGet(HttpServletRequest req, HttpServletResponse

    res)

     throws ServletException, IOException {

     res.setContentType("text/html");

     PrintWriter out = res.getWriter();

     out.print("");

     // connecting to database

     Connection con = null;

     Statement stmt = null;

     ResultSet rs = null;

     try {

     Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

     con=DriverManager.getConnection("jdbc:odbc:odbc_exmp")

    ;

     stmt = con.createStatement();

     // displaying records

     rs = stmt.executeQuery("SELECT * FROM Names");

     out.print("

\"");

     out.print( req.getRequestURI() );

     out.print("\" method=\"post\">");

     out.print("\"hidden\" name=\"id\"");

     out.print(" value=\"0\">");

     out.print("\"submit\" value=\" \">");

     out.print(" Display Records

");

     out.print("First & Last Names :

");

     while(rs.next()) {

     out.print("\"");

     out.print( req.getRequestURI() );

     out.print("\" method=\"post\">");

     out.print("\"hidden\"");

     out.print(" name=\"id\" value=\"");

     out.print( rs.getObject(1).toString() );

     out.print("\">");

     out.print("\"text\"");

     out.print(" name=\"first\" value=\"");

     out.print( rs.getObject(2).toString() );

     out.print("\">");

     out.print("\"text\"");

     out.print(" name=\"last\" value=\"");

     out.print( rs.getObject(3).toString() );

     out.print("\">");

     out.print(" \"submit\"");

     out.print(" value=\" \">");

     out.print(" Update Record
");

     out.print("");

     }

     } catch (Exception e) {

     throw new ServletException(e);

     } finally {

     try {

     if(rs != null) {

     rs.close();

     rs = null;

     }

     if(stmt != null) {

     stmt.close();

     stmt = null;

     }

     if(con != null) {

     con.close();

     con = null;

     }

     } catch (SQLException e) {}

     }

     out.print("");

     out.print("\">\"");

     out.print( req.getRequestURI() );

     out.print("\">Back

");

     out.print("");

     out.close();

     }

     public void doPost(HttpServletRequest req, HttpServletResponse

    res)

     throws ServletException, IOException {

     res.setContentType("text/html");

     PrintWriter out = res.getWriter();

     out.print("");

     out.print("

"); 

     out.print("ID\t");

     out.println("First Name\tLast Name\n");

     // receiving parameters

     String first = req.getParameter("first").trim();

     String last = req.getParameter("last").trim();

     int id;

     try {

     id = Integer.parseInt(req.getParameter("id").trim());

     } catch (NumberFormatException e) {

     throw new ServletException(e);

     }

     boolean proceed = false;

     if(first != null && last != null)

     if(first.length() > 0 && last.length() > 0)

     proceed = true;

     // connecting to database

     Connection con = null;

     Statement stmt = null;

     ResultSet rs = null;

     PreparedStatement ps = null;

     try {

     Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

     con=DriverManager.getConnection("jdbc:odbc:odbc_exmp")

    ;

     String sql = "UPDATE Names SET first_name=?";

     sql += ", last_name=? WHERE ID=?";

     ps = con.prepareStatement(sql);

     stmt = con.createStatement();

     // updating records

     if(proceed) {

     ps.setString(1, first);

     ps.setString(2, last);

     ps.setInt(3, id);

     ps.executeUpdate();

     }

Report this document

For any questions or suggestions please email
cust-service@docsford.com