DOC

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

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

    Beginner Using Servlets to display, insert and update records in

    database.(2)

作者;spring.z

email: spring.z@elong.com

日期;2001-7-3 9:10:13

Inserting records into 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 insert records into the

    database. If you have followed my earlier article about 'Displaying Records from 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 Insert Records ?

    To insert records into the database we will have to learn about another JDBC class, PreparedStatement. Although we can insert

    records using the Statement class we discussed in the last article, the INSERT 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.

    Note that not all database vendors support PreparedStatement class but still it is not a bad habit to use this class so that the ones that do support PreparedStatement class get the extra efficiency.

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 = "INSERT INTO Names(first_name, last_name) VALUES (?,?)";

     // 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 ) containing SQL

    statement.

    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 two places where I will put different values

depending on the values inserted 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.

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

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

     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 INSERT, 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 enter his first and last name and when presses the 'submit' button the records are inserted into the database using the methods we just discussed.

InsertServlet :

Create a new InsertServlet.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 InsertServlet.java file :

package com.stardeveloper.servlets.db;

import java.sql.*;

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class InsertServlet extends HttpServlet {

     public void doGet(HttpServletRequest req, HttpServletResponse

    res)

     throws ServletException, IOException {

     res.setContentType("text/html");

     PrintWriter out = res.getWriter();

     out.print("");

     out.print("

\"");

     out.print( req.getRequestURI() );

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

     out.print("First Name :
");

     out.print("\"text\" name=\"first\">
");

     out.print("Last Name :
");

     out.print("\"text\" name=\"last\">");

     out.print("

\"submit\" value=\" \">");

     out.print(" Insert Record");

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

     out.print(" Display Records");

     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.println("ID\tFirst Name\tLast Name\n");

     // receiving parameters

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

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

     boolean proceed = false;

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

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

     proceed = true;

     // connecting to database

     Connection con;

     Statement stmt;

     ResultSet rs;

     PreparedStatement ps;

     try {

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

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

     String sql = "INSERT INTO Names(first_name,");

     sql += " last_name) VALUES (?,?)";

     ps = con.prepareStatement(sql);

     stmt = con.createStatement();

     // inserting records

     if(proceed) {

     ps.setString(1, first);

     ps.setString(2, last);

     ps.executeUpdate();

     }

     // displaying records

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

     while(rs.next()) {

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

     out.print("\t");

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

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

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

     out.print("\n");

     }

     } catch (SQLException e) {

     throw new ServletException(e);

     } catch (ClassNotFoundException e) {

     throw new ServletException(e);

     } finally {

     try {

     if(rs != null)

     rs.close();

     if(stmt != null)

     stmt.close();

     if(ps != null)

     ps.close();

     if(con != null)

     con.close();

     } catch (SQLException e) {}

     }

     out.print("");

     out.close();

     }

}

    Start your application server and point your browser to http://localhost:8080/star/servlet/com.stardeveloper.servlets.db.InsertServletto see the Servlet on your computer. To see the demo please move on to the last page of this article.

    For explanation of InsertServlet code above, please proceed to the next page.

Explanation :

    Our InsertServlet class extends from HttpServlet class and overrides two methods; doGet() and doPost(). In doGet() we simply

display a Form to the user with two input fields for first and

    last names and two submit buttons, one for inserting and the other one for displaying records.

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

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

     boolean proceed = false;

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

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

     proceed = true;

    In doPost() we retrieve the first and last name values entered by the user using HttpServletRequest.getParameter() method.

    Using a double if statement we make sure that we are not entering null values into the database. If user has entered both first and

    last name then we proceed.

     Connection con;

     Statement stmt;

     ResultSet rs;

     PreparedStatement ps;

    We declare the objects we are going to use to interact with the database.

Report this document

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