Insert data into table java servlet

Insert data into table java servlet

Posted in : Java Posted on : July 6, 2011 at 8:10 PM Comments : [ 0 ]

In this section we will discuss how can we insert a data into the table.

Insert data into table java servlet

In this section we will discuss how can we insert a data into the table.

In the given example I used the insert query statement for insert data into the table. Further since the executeUpdate("") returns an integer value if it updated the statement otherwise returns '0' if the SQL statement does not return anything, so I put it into the 'if' statement for verifying of its updation. Next I put the executeQuery statement into the ResultSet object for displaying the table contents.

Example :

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.DriverManager;

public class InsertInTable extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
PrintWriter pw = res.getWriter();
Statement stmt;
Connection con;
ResultSet rs;
try {
con = DriverManager.getConnection("jdbc:odbc:dataInsert");
stmt = con.createStatement();
int i = stmt.executeUpdate("insert into data values ('Bipul', 24)");
if (i != 0) {
pw.println("Record has been inserted successfully<br>");
} else {
pw.println("Inserting record get failure");
rs = stmt.executeQuery("SELECT * FROM data");
pw.println("name\t age");
while ( {
pw.println("<br>" + rs.getString(1) + ",\t " + rs.getInt(2));
} catch (Exception e) {


<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="" xmlns:xsi="" xsi:schemaLocation="">

Output :

When you will execute the above example you will find the following output :

After executing this example database also be updated by the new value as :

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image

Tutorial Topics