Servlet Database Access
π
2026-06-19 | π Servlet
This tutorial assumes you already understand how JDBC applications work. Before you start learning about Servlet database access, please visit (#) to set up the relevant drivers and configuration.
> **Note:**
>
>
> You can download the jar file provided by this site: **[mysql-connector-java-5.1.39-bin.jar](http://static.example.com/download/mysql-connector-java-5.1.39-bin.jar)**
>
>
> In a Java project, you just need to import mysql-connector-java-5.1.39-bin.jar in Eclipse to run the Java project.
>
>
> However, in an Eclipse web project, when executing `Class.forName("com.mysql.jdbc.Driver");`, it will not look for the driver. Therefore, in this example, we need to copy mysql-connector-java-5.1.39-bin.jar to the lib directory under Tomcat.
Starting from the basic concepts, let's create a simple table and insert a few records into it.
* * *
## Creating Test Data
Next, we will create the TUTORIAL database in MySQL and create the `websites` table with the following structure:
```sql
CREATE TABLE `websites` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` char(20) NOT NULL DEFAULT '' COMMENT 'Site Name',
`url` varchar(255) NOT NULL DEFAULT '',
`alexa` int(11) NOT NULL DEFAULT '0' COMMENT 'Alexa Ranking',
`country` char(10) NOT NULL DEFAULT '' COMMENT 'Countries',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
Insert some data:
```sql
INSERT INTO `websites` VALUES ('1', 'Google', 'https://www.google.cm/', '1', 'USA'), ('2', 'Taobao', 'https://www.taobao.com/', '13', 'CN'), ('3', '', 'https://example.com', '5892', ''), ('4', 'Weibo', 'http://weibo.com/', '20', 'CN'), ('5', 'Facebook', 'https://www.facebook.com/', '3', 'USA');
The data table is displayed as follows:
!(#)
* * *
* * *
The following example demonstrates how to use a Servlet to access the TUTORIAL database.
```java
package com.tutorial.test;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class DatabaseAccess
*/
@WebServlet("/DatabaseAccess")
public class DatabaseAccess extends HttpServlet {
private static final long serialVersionUID = 1L;
// JDBC Driver Name and Database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/TUTORIAL";
// Database username and password, need to set according to your own configuration
static final String USER = "root";
static final String PASS = "123456";
/**
* @see HttpServlet#HttpServlet()
*/
public DatabaseAccess() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection conn = null;
Statement stmt = null;
// Set response content type
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String title = "Servlet Mysql Test - ";
String docType = "n";
out.println(docType +
"n" +
"
" + title + "n" +
"n" +
"" + title + "
n");
try{
// Register JDBC Driver
Class.forName("com.mysql.jdbc.Driver");
// Open a Connection
conn = DriverManager.getConnection(DB_URL,USER,PASS);
// Execute SQL Query
stmt = conn.createStatement();
String sql;
sql = "SELECT id, name, url FROM websites";
ResultSet rs = stmt.executeQuery(sql);
// Expand ResultSet Database
while(rs.next()){
// Retrieve by Field
int id = rs.getInt("id");
String name = rs.getString("name");
String url = rs.getString("url");
// Output Data
out.println("ID: " + id);
out.println(", Site Name: " + name);
out.println(", Site URL: " + url);
out.println("
");
}
out.println("");
// Close after completion
rs.close();
stmt.close();
conn.close();
} catch(SQLException se){
// Handling JDBC Errors
se.printStackTrace();
} catch(Exception e){
// Handle Class.forName Errors
e.printStackTrace();
}finally{
// Finally, the block for closing resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
Now let's compile the above Servlet and create the following entries in the `web.xml` file:
```xml
....
DatabaseAccess
com.tutorial.test.DatabaseAccess
DatabaseAccess
/TomcatTest/DatabaseAccess
....
Now call this Servlet, enter the link: http://localhost:8080/TomcatTest/DatabaseAccess, and the following response will be displayed:
!(#)