·您的位置: 首页 » 资源教程 » 编程开发 » JAVA、JSP » Beginner: Using Servlets to display, insert and update records in database.(2)

Beginner: Using Servlets to display, insert and update records in database.(2)

类别: JAVA教程  评论数:0 总得分:0
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("<html><body>");
                
        out.print("<form action=/"");
        out.print( req.getRequestURI() );
        out.print("/" method=/"post/">");
        out.print("First Name :<br>");
        out.print("<input type=/"text/" name=/"first/"><br>");
        out.print("Last Name :<br>");
        out.print("<input type=/"text/" name=/"last/">");
        out.print("<br><br><input type=/"submit/" value=/" /">");
        out.print("   Insert Record");
        out.print("    <input type=/"submit/" value=/" /">");
        out.print("   Display Records</form>");
        
        out.print("</body></html>");

        out.close();
    }
    
    public void doPost(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
        
        res.setContentType("text/html");
        PrintWriter out = res.getWriter();
        
        out.print("<html><body>");

        out.print("<code><pre>");
        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("</body></html>");
        out.close();
    }
}
Start your application server and point your browser to http://localhost:8080/star/servlet/com.stardeveloper.servlets.db.InsertServlet to 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.

    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    con=DriverManager.getConnection("jdbc:odbc:odbc_exmp");
We load the Sun\'s JDBC/ODBC driver and establish connection to our database using the DSN \'odbc_exmp\'. Notice that this is the same database we used in \'Displaying Records from the Database\'. Please consult that article to see the steps of creating such a database and assigning DSN.

    String sql = "INSERT INTO Names(first_name,");
    sql += " last_name) VALUES (?,?)";
    ps = con.prepareStatement(sql);
    stmt = con.createStatement();
We build the SQL statement which we will use to insert records into the database. Next we create the PreparedStatement and Statement objects using Connection object\'s methods.

    if(proceed) {
        ps.setString(1, first);
        ps.setString(2, last);
        ps.executeUpdate();
    }
Next we set the two \'?\' mark parameters in our PreparedStatement object and insert the records using PreparedStatement.executeUpdate() method.

    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");
    }
We create our ResultSet object by executing the SELECT query. We then iterate through the records and display it to the user. Notice that the new record we just inserted will also be visible to the user during this iteration.

    if(rs != null)
        rs.close();
    if(stmt != null)
        stmt.close();
    if(ps != null)
        ps.close();
    if(con != null)
        con.close();
Close all the objects that we created.

I haven\'t mentioned try..catch statements that we used to catch different exceptions that may be thrown during opening and closing of database connection.

On the next page I sum up what we learned in this article.

Summary :

In this step by step tutorial we learned what is PreparedStatement class and how to use it to build fast SQL statements. We then moved forward to build a simple Form application in which a user enters his first and last name and these values are inserted into the database. After that all the names entered are displayed to user.

The database we used in this article was a Microsoft Access database \'odbc_exmp.mdb\' that we built in \'Displaying Records from the Database\' article. The driver we used was JDBC/ODBC driver, this driver comes with Java Development Kit so you don\'t need to download and install it separately. For more information on how we built the \'odbc_exmp.mdb\' database and what are different types JDBC drivers please consult the above mentioned article.

That\'s it for this article. Kindly post your questions in the Forum. Thanks.

There is no associated material for download
Click here to see the demo



-= 资 源 教 程 =-
文 章 搜 索
关键词:
类型:
范围:
纯粹空间 softpure.com
Copyright © 2006-2008 暖阳制作 版权所有
QQ: 15242663 (拒绝闲聊)  Email: faisun@sina.com
 纯粹空间 - 韩国酷站|酷站欣赏|教程大全|资源下载|免费博客|美女壁纸|设计素材|技术论坛   Valid XHTML 1.0 Transitional
百度搜索 谷歌搜索 Alexa搜索 | 粤ICP备19116064号-1