Signup · Login
Stardeveloper.com  
Home · Tutorials · Forums · ASP.NET Newsletter Application · Web Hosting Plans · Faisal Khan's Blog · Contact
Search Stardeveloper.com
Newsletter
Enter your email address to receive full length articles at Stardeveloper:


Article Categories
.NET  .NET
  ASP (16)
  ASP.NET (41)
  ADO (16)
  ADO.NET (11)
  COM (6)
  Web Services (4)
  C# (1)
  VB.NET (3)
  IIS (2)

J2EE  J2EE
  JSP (15)
  Servlets (9)
  Web Services (1)
  EJB (4)
  JDBC (4)
  E-Commerce (1)
  J2ME (1)
  Products (1)
  Applets (1)
  Patterns (1)

Main Category  Other
  Website Maintenance (3)
Log In
UserName Or Email:

Password:

Auto-Login:

Hosted by Securewebs.com
 
Home : J2EE : Servlets : Inserting records into the Database with Java Servlets
 
Read full length articles at Stardeveloper using Twitter Follow on Twitter Facebook Facebook fan page Email Get Articles via Email RSS Get Articles via RSS Feed
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 = 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;
		sql = "INSERT INTO Names(first_name, 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.

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");
	}

Previous ( 1 Gone )( 1 Remaining ) Next

Comments/Questions ( Threads: 10, Comments: 11 )
    Contains 1 or more replies by the Author of this Article.
    Contains 1 or more replies by Faisal Khan.

  1. connection establish problem orcle 9i with servlets
  2. Java servlet 'inserting' or 'retrieving' into/from SQLite database
  3. Retreving data from Database using Servlets
  4. inserting values in database using servlet and JSP
  5. Connection with Oracle database through JSP
  6. oracle connection
  7. java beans and jsp
  8. insertion
  9. Hi Again
  10. Inserting values into the databse at runtime ( 1 Reply )

Post Comments/Questions

In order to post questions/comments, you must be logged-in. If you are not a member yet, then signup, otherwise login. Once you login then come back to this page and you'll see a form right here which will allow you to post comments/questions.

Please note, one of the benefits of signing up is to be notified immediately by email everytime you receive a reply to the thread you have subscribed.

 
© 1999 - 2010 Stardeveloper.com, All Rights Reserved.