Database connection in Servlet

Purpose:

    How to connect your Servlet with Database?

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

import java.io.*;
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"
		
		try
		{
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			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"
			
			if(rs.next())
			{
				out.println("<h3> Name=</h3>" +rs.getString("s_name")); // Printing Name from Database
				out.println("<br> Address=" +rs.getString("address"));  // Printing Address from Database
			}
			else
			{
				out.println("<h3> ID is not exists</h3>"); // If no such ID found in Database
			}
		}
		catch(Exception e)
		{
			out.println(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" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

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

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

</form>
</body>
</html>

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

OUTPUT

Advertisements