Database connection in Servlet


    How to connect your Servlet with Database?

1) Create “”, as servlet file (don’t know how to create a servlet file in Eclipse? Refer to our post: “ Servlet in Eclipse IDE“)

import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*; // for database purpose
public class MyServlet extends HttpServlet
	Connection con;
	Statement stmt;
	ResultSet rs;
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
		response.setContentType("text/html"); // informing the client that which format of data/response will be send
		PrintWriter out= response.getWriter(); 
		String name= request.getParameter("num");
		// will retrieve "NUM" field value entered by user using "getParameter()"
		// and store in STRING "name"
			con= DriverManager.getConnection("Jdbc:Odbc:dbs123");
			stmt= con.createStatement();
			rs=stmt.executeQuery("Select * from Student where s_name= '"+name+"' ");
			// Retrieving all columns from Database where "name" matches
			// Name of table is "Student"
				out.println("<h3> Name=</h3>" +rs.getString("s_name")); // Printing Name from Database
				out.println("<br> Address=" +rs.getString("address"));  // Printing Address from Database
				out.println("<h3> ID is not exists</h3>"); // If no such ID found in Database
		catch(Exception e)


2) Create “index.html”, as HTML file (you can refer: “How to add HTML file in your Servlet Program using Eclipse“)

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

<form action="MyServlet" method="get">
Enter the ID of Student
<input type="text" name="num"><br> 

<input type="Submit" value="Submit">


3) Create “DBServlet” database file

Design View of database

4) Configure database in Administrative Tools from Control Panel
ODBC –> ADD –> Microsoft Access Driver (*.mdb,*.accdb)

Under “Data Source Name” enter: “dbs123” (as mentioned in Servlet file)
Click on “Select”
from “C” directory, choose appropriate database, i.e “DBServlet.accdb”
Click on “OK”

5) Press “CTRL”+ F11