Tutorials Logic, IN info@tutorialslogic.com

Servlet Database Connectivity JDBC, Connection Pooling: Tutorial, Examples, FAQs & Interview Tips

Servlet Database Connectivity JDBC, Connection Pooling

Servlet Database Connectivity JDBC, Connection Pooling is an important Servlet topic because it appears in real projects, debugging sessions, and interviews. Learn the meaning first, then connect it to a small working example so the rule does not stay abstract.

For this page, focus on what problem Servlet Database Connectivity JDBC, Connection Pooling solves, where developers usually make mistakes, and how to verify the result. The audit note for this lesson was: limited checklist/practice/mistake/FAQ notes .

A strong understanding of Servlet Database Connectivity JDBC, Connection Pooling should include syntax, behavior, one realistic use case, one failure case, and one quick way to check your work with tools or output.

Servlet Database Connectivity JDBC Connection Pooling should be studied as a practical Servlet lesson, not as a label. Start by naming the input, the rule that changes the input, and the result a learner should be able to predict after reading the page.

In the servlet > database-connectivity page, the notes should connect the definition with a working scenario, a mistake that beginners actually make, and the exact check that proves the fix. That makes the topic useful for coding, debugging, and interview revision.

JDBC with Servlet

Servlets commonly interact with databases using JDBC (Java Database Connectivity). The typical pattern is: Servlet receives request -> calls DAO (Data Access Object) -> DAO uses JDBC -> returns data -> Servlet forwards to JSP view.

DAO Pattern with JDBC

DAO Pattern with JDBC
package com.example.dao;

import com.example.model.User;
import java.sql.*;
import java.util.*;

public class UserDAO {

    // CREATE
    public boolean createUser(User user) throws SQLException {
        String sql = "INSERT INTO users (username, email, password) VALUES (?, ?, ?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getEmail());
            ps.setString(3, user.getPassword()); // Hash in real app!
            return ps.executeUpdate() > 0;
        }
    }

    // READ - Get by ID
    public User getUserById(int id) throws SQLException {
        String sql = "SELECT * FROM users WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, id);
            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next()) {
                    return mapRow(rs);
                }
            }
        }
        return null;
    }

    // READ - Get all
    public List<User> getAllUsers() throws SQLException {
        List<User> users = new ArrayList<>();
        String sql = "SELECT * FROM users ORDER BY username";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql);
             ResultSet rs = ps.executeQuery()) {
            while (rs.next()) {
                users.add(mapRow(rs));
            }
        }
        return users;
    }

    // UPDATE
    public boolean updateUser(User user) throws SQLException {
        String sql = "UPDATE users SET email = ? WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, user.getEmail());
            ps.setInt(2, user.getId());
            return ps.executeUpdate() > 0;
        }
    }

    // DELETE
    public boolean deleteUser(int id) throws SQLException {
        String sql = "DELETE FROM users WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, id);
            return ps.executeUpdate() > 0;
        }
    }

    private User mapRow(ResultSet rs) throws SQLException {
        User u = new User();
        u.setId(rs.getInt("id"));
        u.setUsername(rs.getString("username"));
        u.setEmail(rs.getString("email"));
        return u;
    }
}

JDBC with Servlet

JDBC with Servlet
package com.example.dao;

import java.sql.*;

public class DBUtil {
    private static final String URL      = "jdbc:mysql://localhost:3306/mydb?useSSL=false";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "password";

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("MySQL Driver not found", e);
        }
    }

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL, USERNAME, PASSWORD);
    }
}

Servlet CRUD Controller

UserServlet - CRUD Controller

UserServlet - CRUD Controller
@WebServlet("/users")
public class UserServlet extends HttpServlet {

    private UserDAO userDAO = new UserDAO();

    // GET /users - List all users
    // GET /users?id=1 - Get specific user
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        try {
            String idParam = req.getParameter("id");
            if (idParam != null) {
                User user = userDAO.getUserById(Integer.parseInt(idParam));
                req.setAttribute("user", user);
                req.getRequestDispatcher("/WEB-INF/views/user-detail.jsp")
                   .forward(req, resp);
            } else {
                List<User> users = userDAO.getAllUsers();
                req.setAttribute("users", users);
                req.getRequestDispatcher("/WEB-INF/views/user-list.jsp")
                   .forward(req, resp);
            }
        } catch (SQLException e) {
            throw new ServletException("Database error", e);
        }
    }

    // POST /users - Create new user
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        User user = new User();
        user.setUsername(req.getParameter("username"));
        user.setEmail(req.getParameter("email"));
        user.setPassword(req.getParameter("password"));
        try {
            userDAO.createUser(user);
            resp.sendRedirect(req.getContextPath() + "/users");
        } catch (SQLException e) {
            throw new ServletException("Database error", e);
        }
    }

    // DELETE /users?id=1 - Delete user
    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        int id = Integer.parseInt(req.getParameter("id"));
        try {
            userDAO.deleteUser(id);
            resp.setStatus(HttpServletResponse.SC_NO_CONTENT); // 204
        } catch (SQLException e) {
            throw new ServletException("Database error", e);
        }
    }
}

Connection Pooling with JNDI DataSource

For production applications, use a connection pool instead of creating a new connection per request. Configure a JNDI DataSource in Tomcat's context.xml:

JNDI DataSource Configuration

JNDI DataSource Configuration
<!-- META-INF/context.xml -->
<Context>
    <Resource name="jdbc/mydb"
              auth="Container"
              type="javax.sql.DataSource"
              maxTotal="20"
              maxIdle="10"
              maxWaitMillis="10000"
              username="root"
              password="password"
              driverClassName="com.mysql.cj.jdbc.Driver"
              url="jdbc:mysql://localhost:3306/mydb?useSSL=false"/>
</Context>

Connection Pooling with JNDI DataSource

Connection Pooling with JNDI DataSource
// Using JNDI DataSource in DAO
import javax.naming.*;
import javax.sql.DataSource;

public class DBUtil {
    private static DataSource dataSource;

    static {
        try {
            Context ctx = new InitialContext();
            dataSource = (DataSource) ctx.lookup("java:comp/env/jdbc/mydb");
        } catch (NamingException e) {
            throw new RuntimeException("JNDI lookup failed", e);
        }
    }

    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection(); // From pool
    }
}

Servlet Database Connectivity JDBC Connection Pooling Java review example

Servlet Database Connectivity JDBC Connection Pooling Java review example
class ServletDatabaseConnectivityJDBCConnectionPoolingReview {
    public static void main(String[] args) {
        String state = "ready";
        System.out.println("Servlet Database Connectivity JDBC Connection Pooling: " + state);
    }
}

Servlet Database Connectivity JDBC Connection Pooling guard example

Servlet Database Connectivity JDBC Connection Pooling guard example
String value = null;
if (value == null) {
    System.out.println("Servlet Database Connectivity JDBC Connection Pooling: handle the missing value before continuing");
}
Key Takeaways
  • Explain the purpose of Servlet Database Connectivity JDBC, Connection Pooling before memorizing syntax.
  • Run or trace one small Servlet example and confirm the output.
  • Test one normal case, one edge case, and one mistake case for Servlet Database Connectivity JDBC, Connection Pooling.
  • Write the rule in your own words after checking the example.
  • Connect Servlet Database Connectivity JDBC, Connection Pooling to a real project scenario instead of treating it as an isolated definition.
Common Mistakes to Avoid
WRONG Memorizing Servlet Database Connectivity JDBC Connection Pooling without the situation where it is useful.
RIGHT Connect Servlet Database Connectivity JDBC Connection Pooling to a concrete Servlet task.
Purpose makes syntax easier to recall.
WRONG Testing Servlet Database Connectivity JDBC Connection Pooling only with the perfect input.
RIGHT Include empty, missing, duplicate, incompatible, or failed cases when relevant.
Real bugs usually appear outside the perfect path.
WRONG Changing code before reading the visible symptom or error message.
RIGHT Inspect the output, state, configuration, or stack trace connected to Servlet Database Connectivity JDBC Connection Pooling.
Evidence keeps debugging focused.
WRONG Memorizing Servlet Database Connectivity JDBC Connection Pooling without the situation where it is useful.
RIGHT Connect Servlet Database Connectivity JDBC Connection Pooling to a concrete Servlet task.
Purpose makes syntax easier to recall.

Practice Tasks

  • Modify the example so it handles a different input or condition.
  • Write one mistake related to Servlet Database Connectivity JDBC, Connection Pooling, then fix it and explain the fix.
  • Summarize when to use Servlet Database Connectivity JDBC, Connection Pooling and when another approach is better.
  • Write a small example that uses Servlet Database Connectivity JDBC Connection Pooling in a realistic Servlet scenario.
  • Change one important value in the Servlet Database Connectivity JDBC Connection Pooling example and predict the result first.

Frequently Asked Questions

The common mistake is memorizing syntax without understanding when the behavior changes or fails.

Remember the problem it solves in Servlet, then attach the syntax or steps to that problem.

You can predict the result of a small example, explain a failure case, and choose it over a nearby alternative for a clear reason.

They often copy the syntax but skip the state, input, dependency, selector, route, type, or configuration that controls the behavior.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.