O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

21.1. Accessing a Database from a Servlet Without DataSource

Problem

You want to access a database from a servlet without a DataSource configuration for the database.

Solution

Use the Java Database Connectivity (JDBC) API to access a java.sql.Connection object that connects the servlet with the database.

Discussion

On occasion, developers require a quick, less elegant solution to accessing a database. This recipe explains how to use the java.sql.DriverManager class to obtain a connection to a datasource in a servlet. The DriverManager class communicates with a database driver, which is software that allows Java code to interact with a particular database, such as MySQL or Oracle.

Tip

The preferred design is to use a javax.sql.Datasource to get a database connection from a connection pool, as described in Recipe 21.2-Recipe 21.6.

Example 21-1 accomplishes this task in its doGet( ) service method.

Example 21-1. A servlet accesses a database using the JDBC API

package com.jspservletcookbook;import java.sql.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class DatabaseServlet extends HttpServlet {

  public void doGet(HttpServletRequest request, 
     HttpServletResponse response) throws ServletException,
       java.io.IOException {
    
        String sql = "select * from athlete";

        Connection conn = null;

        Statement stmt = null;

        ResultSet rs = null;

        ResultSetMetaData rsm = null; response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter( ); out.println( "<html><head><title>Servlet ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required