Core Java| JSP| Servlets| XML| EJB| JEE5| Web Services| J2ME| Glossary| Questions?

 

 

 

 

 

 

 

 

 

 

 

 

 

Search Tutorials

Latest Questions
Comments
 
insert into statement in sql using servlets 
 

In this tutorial we are going to learn how we can insert a value from a html form in the table stored in the database.

 

insert into statement in sql using servlets

                         

In this tutorial we are going to learn how we can insert a value from a html form in the table stored in the database. 

For inserting the values in the database table it is required to have a table in which we are going to insert the values. Now make one jsp page or  html page where we will insert the values. In this program we have made one simple enquiry form which will get stored in the database table and when the data gets entered into the database then you will get a message. Make one submit button for inserting the values into the database. Firstly this values will go to the controller and retrieved the variables enter in the form by the method getParameter() method of the request object. Pass a query to insert the values retrieved from the html form. To set the values into the database use setString() method. To retrieve the values from the database use getString() method of the PreparedStatement object.

The code of the program is given below:

<html>

<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<meta name="GENERATOR" content="Microsoft FrontPage 4.0">
<meta name="ProgId" content="FrontPage.Editor.Document">
<title>New Page 1</title>
</head>

<body>

<form method="POST" action="/sqlStatServlet/ServletUserEnquiryForm">
  <!--webbot bot="SaveResults" U-File="fpweb:///_private/form_results.txt"
  S-Format="TEXT/CSV" S-Label-Fields="TRUE" -->
  <p>User Id:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
         <input type=
"text" name="userId" size="20"></p>
  <p>First Name:&nbsp;&nbsp; <input type="text" name="firstname" size="20"></p>
  <p>Surname: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text" name="surname" size="20"></p>
  <p>Address1:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text" name="address1" size="20"></p>
  <p>Address2:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text" name="address2" size="20"></p>
  <p>Town:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text" 
                                                       
name="town" size="20"></p>
  <p>City:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  <input type="text" name="country" size="20"></p>
  <p>Zip code:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text" name="zipcode" size="20"></p>
  <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  <input type="submit" value="Submit" name="B1"></p>
</form>

</body>

</html>

ServletUserEnquiryForm.java

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

public class ServletUserEnquiryForm extends HttpServlet{
  public void init(ServletConfig configthrows ServletException{
    super.init(config);
  }
  /**Process the HTTP Get request*/
  public void doPost(HttpServletRequest req, HttpServletResponse res
                                
throws ServletException, IOException{
    String connectionURL = "jdbc:mysql://localhost/zulfiqar";
    Connection connection=null;
    ResultSet rs;
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    //get the variables entered in the form
    String uId = req.getParameter("userId");
    String fname = req.getParameter("firstname");
    String sname = req.getParameter("surname");
    String address1 = req.getParameter("address1");
    String address2 = req.getParameter("address2");
    String town = req.getParameter("town");
    String county = req.getParameter("country");
    String zipcode = req.getParameter("zipcode")
    try {
      // Load the database driver
      Class.forName("org.gjt.mm.mysql.Driver");
      // Get a Connection to the database
      connection = DriverManager.getConnection(connectionURL, "root""admin")
      //Add the data into the database
      String sql = "insert into emp_details values (?,?,?,?,?,?,?,?)";
      PreparedStatement pst = connection.prepareStatement(sql);
      pst.setString(1, uId);
      pst.setString(2, fname);
      pst.setString(3, sname);
      pst.setString(4, address1);
      pst.setString(5, address2);
      pst.setString(6, town);
      pst.setString(7, county);
      pst.setString(8, zipcode);
      int numRowsChanged = pst.executeUpdate();
      // show that the new account has been created
      out.println(" Hello : ");
      out.println(" '"+fname+"'");
      pst.close();
    }
    catch(ClassNotFoundException e){
      out.println("Couldn't load database driver: " + e.getMessage());
    }
    catch(SQLException e){
      out.println("SQLException caught: " + e.getMessage());
    }
    catch (Exception e){
      out.println(e);
    }
    finally {
      // Always close the database connection.
      try {
        if (connection != nullconnection.close();
      }
      catch (SQLException ignored){
        out.println(ignored);
      }
    }
  }
}

web.xml file for this program:

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
 PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
 <servlet>
 <servlet-name>Zulfiqar</servlet-name>
 <servlet-class>ServletUserEnquiryForm</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>Zulfiqar</servlet-name>
 <url-pattern>/ServletUserEnquiryForm</url-pattern>
 </servlet-mapping>
</web-app>

The output of the program is given below:

Login.html form for the data input:

The output of the input data:

Download this example:

                         

» View all related tutorials
Related Tags: c ide orm table data form io make type column field name columns change this id nsis war tab row

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

6 comments so far (
post your own) View All Comments Latest 10 Comments:

i want to be able to update my data-base through the internet using jsp. please how can i do this.
thanks.

Posted by cues on Saturday, 04.5.08 @ 01:15am | #55355

dear sir/madam
i am facing problem in jsp. i want to insert form into database using jsp page.

how to fetch data from html page and how to fetch on jsp page and insert into database.

please reply..
plz.............

i am trying to solve problem last 2 days..

Posted by sandip on Thursday, 03.27.08 @ 11:58am | #54470

Without using submit button insert the values in html page automatic insert the values in db using in ajax in java

Posted by gupta on Tuesday, 02.19.08 @ 16:57pm | #49082

HI,

You use the following code in JSP page.

String connectionURL = "jdbc:mysql://localhost/zulfiqar";
Connection connection=null;
ResultSet rs;
res.setContentType("text/html");
PrintWriter out = res.getWriter();
//get the variables entered in the form
String uId = req.getParameter("userId");
String fname = req.getParameter("firstname");
String sname = req.getParameter("surname");
String address1 = req.getParameter("address1");
String address2 = req.getParameter("address2");
String town = req.getParameter("town");
String county = req.getParameter("country");
String zipcode = req.getParameter("zipcode");
try {
// Load the database driver
Class.forName("org.gjt.mm.mysql.Driver");
// Get a Connection to the database
connection = DriverManager.getConnection(connectionURL, "root", "admin");
//Add the data into the database
String sql = "insert into emp_details values (?,?,?,?,?,?,?,?)";
PreparedStatement pst = connection.prepareStatement(sql);
pst.setString(1, uId);
pst.setString(2, fname);
pst.setString(3, sname);
pst.setString(4, address1);
pst.setString(5, address2);
pst.setString(6, town);
pst.setString(7, county);
pst.setString(8, zipcode);
int numRowsChanged = pst.executeUpdate();
// show that the new account has been created
out.println(" Hello : ");
out.println(" '"+fname+"'");
pst.close();
}
catch(ClassNotFoundException e){
out.println("Couldn't load database driver: " + e.getMessage());
}
catch(SQLException e){
out.println("SQLException caught: " + e.getMessage());
}

Thanks

Posted by Vinod on Tuesday, 02.12.08 @ 12:26pm | #47989

I want to insert data into mysql database using jsp.How can i do it?

Posted by Lisa on Tuesday, 02.12.08 @ 11:51am | #47985

Great web site really useful for developers

Posted by vasu on Tuesday, 04.10.07 @ 15:21pm | #13714

Training Courses
Tell A Friend
Your Friend Name
Software Solutions
Least Viewed
Most Rated
Recently Viewed
Search Tutorials

 

 
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Indian Software Development Company | iPhone Development Company in India | Flex Development Company in India | Java Training Delhi | Java Training at Noida |

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2008. All rights reserved.