Prepared statement insert in java

Prepared statement insert in java

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

In this example we will discuss how can we insert a data into database using Prepared Statement.

Prepared statement insert in java

In this example we will discuss how can we insert a data into database using Prepared Statement.

To accomplish the solution of this problem I used the PreparedStatement class of java.sql package. Benefit of the use of PreparedStatement is that it is compiled only once, then after it is compiled all times with that format no matter if there are dynamic parameters. In other word we can say PreparedStatement contains a pre compiled SQL statement so the DBMS doesn't have to require to compile the PreparedStatement first, it only run the PreparedStatement SQL statement, that's why the PreparedStatement is much faster than over all time. Further I have used the prepareStatement() method of Connection interface which creates an object of PreparedStatement that sends a SQL statements to the database into its parameter.

Example :


<title>Store data into database</title>
<form method= "get" action="/datainsert/DataInsertTable">
<p>Name <input type="text" name="name"></input></p>
<p>Age <input type="text" name="age"></input></p>
<p>Password <input type="password" name="psw"></input></p>
<p> <input type="submit" value="submit"></input></p>

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DataInsertTable extends HttpServlet
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException
PrintWriter pw = res.getWriter();
Connection con;
PreparedStatement ps;
ResultSet rs;

String nm = req.getParameter("name");
String ag = req.getParameter("age");
String pass = req.getParameter("psw");
con = DriverManager.getConnection("jdbc:odbc:dataInsert");
ps = con.prepareStatement("INSERT INTO data (name,password) values(?,?)");
int i = ps.executeUpdate();
pw.println("Your Data has been successfully stored in database");
pw.println("Hello <b>"+nm+"</b><br>");
pw.println("Your password is "+pass);
pw.println("sorry failed to store ! try again......");

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 get the following output :

first entry

second entry

Record stored in database.

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:

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

Tutorial Topics