How To Connect Servlet to MySQL Database in Eclipse

In the previous article, we discuss database connectivity in Servlet. Now, let us see how to connect servlet to MySQL database in eclipse? Prerequisite:- Database Connectivity in Servlet.

Step1) Create a new Dynamic Web Project. New => Dynamic Web Project => Enter Project Name.

Here we are choosing the project name as “DBMySQLEclipse” => Next => Next => Select option to generate web.xml deployment descriptor.

Step2) Add MySQL connector jar file to the lib folder of the web application.

This is the most important part of this example. Download the latest suitable JDBC driver of the MySQL database. Open the downloaded zip file and extract it. The mysql-connector-java-<version>.jar is the main Jar file.

To add that jar file, just copy it (select jar file, CTRL + C) and paste it (CTRL + V) to the lib folder of the Eclipse web project. The lib folder is located at DBMySQLEclipse\src\main\webapp\WEB-INF\lib.

How to connect servlet to database in eclipse

Or, you can do the same by configuring the build path of the web application, and deployment assembly. Compared to this approach the copy-paste option is easier. Select web application => Right Click => Build Path => Configure Build Path => Libraries => Select Classpath => Add External Jar Files => Apply => Apply and Close. By default, the jar files added to the classpath won’t come to the lib folder. To do that open properties of the web application => Deployment assembly => Add => Java Build Path Entities => Next => Select Jar file => Finish => Apply => Apply and close. Actually, we won’t see any jar file added to the lib folder, but it will be placed dynamically while the deployment of the web application. 

Step3:- Develop the resources.

Web Application Example for Servlet to MySQL Database in Eclipse

Web Application Description:- In the MySQL database, we have a “student” table. In a web application, there will be an HTML form that gets the student number (sno) as input and passes it to the servlet component. Based on the passed sno fetch the sname, sadd and avg details of the student and display them as result. Get more about Java to database connectivity here:- Java to MySQL database connection.

10Sophia Manchester72
Database Connectivity in Servlet - HTML Form
Database Connectivity in Servlet - Student Found and Details displayed
Output When Student ID Found
Database Connectivity in Servlet - Student not found
Output When Student ID Found

The HTML file (input.html),

<h1 style="color:blue">Find Student details</h1>
<form action="student-details" method="post">
   Student No: <input type="text" name="sid"/><br>
   <input type="submit" value="Get Student Details">
   <input type="reset" value="Cancel">

The servlet component ( for Servlet to MySQL database,


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

public class GetStudentServlet extends HttpServlet {
   // SQL query
   private static final String SELECT_STUDENT_QUERY = 

   public void doGet(HttpServletRequest req, HttpServletResponse res) 
         throws ServletException, IOException {

      // variables
      PrintWriter pw = null;
      int sno = 0;
      Connection con = null;
      PreparedStatement ps = null;
      ResultSet rs = null;
      boolean flag = false;

      // set content type
      // get Writer
      pw = res.getWriter();

      // get form data
      sno = Integer.parseInt(req.getParameter("sid"));

      try {
         // register JDBC driver
         // create JDBC connection
         con = DriverManager.getConnection(
               "jdbc:mysql:///knowprogram", "root", "Know9@Program");
         // compile SQL query and store it in
         // PreparedStatement object
         if (con != null)
            ps = con.prepareStatement(SELECT_STUDENT_QUERY);
         // set input value to query parameter
         if (ps != null)
            ps.setInt(1, sno);
         // execute the query
         if (ps != null)
            rs = ps.executeQuery();

         // process the result
         if (rs != null) {
            while ( {
               // display result
               flag = true;
               pw.println("<h1>Student Details, </h1>" 
                    + "Name: " + rs.getString("SNAME") + "<br>" 
                   + "Address: " + rs.getString("SADD") + "<br>" 
                    + "Average: " + rs.getDouble("AVG") + "<br>");

         // Student not found
         if (!flag) {
            pw.println("<h1>Student Not Found.</h1>");

      } catch (SQLException se) {
         pw.println("Error Occured");
      } catch (Exception e) {
         pw.println("Unknown Exception Occured");
      } finally {
         // close JDBC connection
         try {
            if (rs != null)
         } catch (SQLException se) {
         try {
            if (ps != null)
         } catch (SQLException se) {
         try {
            if (con != null)
         } catch (SQLException se) {

         // Link to home
         pw.println("<h3><a href='input.html'>Home</a></h3>");
         // close stream

   public void doPost(HttpServletRequest req, HttpServletResponse res) 
         throws ServletException, IOException {
      doGet(req, res);

Since it was a very basic and simple web application, therefore we are hardcoding the technical input values like JDBC driver class name, URL, database username, and password. But it is always recommended to gather those values from the web.xml file using <init-param> or <context-param> through ServletConfig/ServletContext values.

The deployment descriptor (web.xml) file,

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

See the source code for this web application (to connect Servlet to MySQL Database in Eclipse) at GitHub.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *