Servlets - Database Access
Servlets - Database Access
This tutorial assumes you have understanding on how JDBC application works. Before starting
with database access through a servlet, make sure you have proper JDBC environment setup
along with a database.
For more detail on how to access database using JDBC and its environment setup you can go
through our JDBC Tutorial .
To start with basic concept, let us create a simple table and create few records in that table as
follows −
Create Table
To create the Employees table in TEST database, use the following steps −
Step 1
C:\>
C:\>cd Program Files\MySQL\bin
C:\Program Files\MySQL\bin>
Step 2
Step 3
https://www.tutorialspoint.com/servlets/servlets-database-access.htm 1/4
10/18/21, 8:39 PM Servlets - Database Access
mysql>
Accessing a Database
Here is an example which shows how to access TEST database using Servlet.
// Database credentials
static final String USER = "root";
static final String PASS = "password";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
https://www.tutorialspoint.com/servlets/servlets-database-access.htm 2/4
10/18/21, 8:39 PM Servlets - Database Access
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n");
try {
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Open a connection
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
//Display values
// Clean-up environment
rs.close();
stmt.close();
conn.close();
} catch(SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch(Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
//finally block used to close resources
try {
if(stmt!=null)
https://www.tutorialspoint.com/servlets/servlets-database-access.htm 3/4
10/18/21, 8:39 PM Servlets - Database Access
stmt.close();
} catch(SQLException se2) {
} // nothing we can do
try {
if(conn!=null)
conn.close();
} catch(SQLException se) {
se.printStackTrace();
} //end finally try
} //end try
}
}
Now let us compile above servlet and create following entries in web.xml
....
<servlet>
<servlet-name>DatabaseAccess</servlet-name>
<servlet-class>DatabaseAccess</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DatabaseAccess</servlet-name>
<url-pattern>/DatabaseAccess</url-pattern>
</servlet-mapping>
....
Now call this servlet using URL http://localhost:8080/DatabaseAccess which would display
following response −
Database Result
https://www.tutorialspoint.com/servlets/servlets-database-access.htm 4/4