Home | Ajax | BioInformatics | Dojo | EAI | EJB | Hibernate | J2ME | Java | Java Glossary | Java Servlets | JavaScript | Jboss | JDBC | JDO | Jmeter | JSF | JSP | JUnit | Maven | MySQL | Spring Framework | SQL | Struts | Technology | WAP | Web Services | XML
Java Servlets
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
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:

                         

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

Latest Tutorials:
Styles in HTML
Style Tags Used in HTM
Check Box in HTML
Action Submit Html
Cascading Style Sheet(
Horizontal Rule Attrib
Horizontal Rule in HTM
Show Hyperlink in HTML
Unordered Lists
Paragraph in HTML
Password Field in HTML
Radio Buttons in HTML
Set Background Colors
Table & the Border att
Text Area in HTML
Text Field in HTML
Use of Text Field
Table Caption in HTM
J2ME Servlet Example
J2ME Cookies Example
J2ME Frame Animation2
J2ME Frame Animation
J2ME RMS Read Write
J2ME Record Data Base
J2ME Audio Record
J2ME Record Listener
J2ME Text Box Example
J2ME Timer Animation
J2ME Vector Example
J2ME Video Control Exa
J2ME Event Handling Ex
J2ME HashTable Example
J2ME Icon MIDlet Examp
J2ME Image Item Exampl
J2ME Image Example
J2ME Item State Listen
J2ME Key Codes Example
J2ME KeyEvent Example
J2ME Label Example
J2ME Random Number
J2ME Read File
J2ME RMS Sorting Examp
J2ME Timer MIDlet Exam
Custom Item in J2ME
Creational Design Patt
Design Patterns
Throwing Run time exce
Grid in Echo3
Creating Table in Echo
JPA Introduction
Java bigdecimal toBigI
Java bigdecimal shortV
Java bigdecimal shortV
Java bigdecimal signum
Java bigdecimal stripT
Java bigdecimal subtra
Java bigdecimal subtra
Java bigdecimal toBigI
Java bigdecimal toEngi
Java bigdecimal toPlai
Java bigdecimal toStri
Java bigdecimal ulp ex
Java bigdecimal unscal
Java bigdecimal valueO
Java bigdecimal valueO
Java bigdecimal valueO
Java bigdecimal setSca
Java bigdecimal setSca
Java bigdecimal scaleB
Java bigdecimal scale
Java bigdecimal round
Java bigdecimal remain
Java bigdecimal remain
Java bigdecimal precis
Java bigdecimal pow me
Java bigdecimal pow ex
Java bigdecimal plus m
Java bigdecimal plus e
Java bigdecimal negate
Java bigdecimal negate
Java bigdecimal multip
Java bigdecimal multip
Java BigDecimal movePo
Java bigdecimal movePo
Java bigdecimal min ex
Java bigdecimal max ex
CheckBox component in
Visibility of Componen
Loading delay componen
Simple input applicati
Opening a new window i
Hello World in Echo3 f
Use of Local Inner cla
JSP bean set property
Java Method Synchroniz
Java Method Return Val
JAVA Method Wait
JDBC vs ORM
Java BigDecimal divide
Java BigDecimal divide
Java String toLowerCase Example
Java String toCharArray Example
Java String substring Example
Java String indexOf Example
Java String startsWith Example
Java String hashCode Example
Java String matches Example
Java String length Example
Java String lastIndexOf Example
Java String isEmpty Example
Java String equalsIgnoreCase Example
Java String equals Example
Java String endsWith Example
Java String copyValueOf Example
Java String contentEquals Example
  EAI Articles
  Java Certification
Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

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 | 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.