Servlet code to insert data into MS SQL database using Tomcat Server

Unlike JSP and PHP Servlet is also server side scripting language. Servlet is Java based, Here this post we are going to illustrate how to add, delete , update and Search data from a form interacting with SQL database.
For consideration we will need tomcat server installed running on the system by default at port 8080 and sql database running on the system.


Create database in Microsoft sql Query analyser .
Create table with 4 fields viz StudentName , ID , Age and Branch.
->Keep ID as  INT and set it as primary key
->keep StudentName as VARCHAR(100)
->keep age as INTEGER
->Keep Branch as VARCHAR(100)

STEP 2 :

This code is only for addition of information to the database

Create a html page as follows:


<h1><u>student form</u></h1>
<body bgcolor="DarkSalmon">
<form name=Student method=POST action=http://localhost:8080/examples/servlet/studentinfo>
<font face="Copperplate Gothic Bold">STUDENT NAME</font face>:<input type="text" name="t1" size="30"><p><br>
<font face="Copperplate Gothic Bold">ID</font face>:<input type="text" name="t2" size="30"><p><br>
<font face="Copperplate Gothic Bold">AGE</font face>:<input type="text" name="t3" size="30"><p><br>
<font face="Copperplate Gothic Bold">BRANCH</font face>:<input type="text" name="t4" size="30"><p><br>
<input type="submit" value="submit">

Now Create a page named which has actual logic to interact with SQL database and insert information.

import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class studentinfo extends HttpServlet
public void doPost(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
PrintWriter out=res.getWriter();
String s1=req.getParameter("t1");
String s2=req.getParameter("t2");
String s3=req.getParameter("t3");
String s4=req.getParameter("t4");
out.println("<html><body><h1>............................servlet running..........:):).......</h1></body></html>");
Connection con=DriverManager.getConnection("jdbc:odbc:student1","sa","sa");
out.println("<html><body><h4>connectiopn established........</h4></body></html>");
String query="insert into studentinfo values('"+s1+"','"+s2+"','"+s3+"','"+s4+"')";
out.println("<html><body><h3>inserting into database.......</h3></body></html>");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(query);
out.println("<html><body><h4>thank you for registrating.......</h4></body></html>");
catch(Exception e)
System.out.println("Error in login:"+e);

inserting to SQL databse using servlet


Post a Comment

If You Are Asking Some Question On This Comment Then Click On Subscribe by email Link