Wednesday, February 7, 2018

How to establish a database connection using JSP

In this post you will learn how to establish a database connection using JSP.The first thing you need to add is a page directive to import the java.sql package for the database code as follows:
<%@ page import="java.sql.*" %>
You'll use a single ResultSet object to hold your database results. Because you'd like this to be
available to the entire page, the next thing you do is declare it in a JSP declaration tag:
<%! ResultSet rs = null; %>
Finally, you establish a connection to the database and retrieve the required data.
Now i will show you a complete code for simple application to connect database.

<!-- JSP Directives -->
<%@ page import="java.sql.*" %>
<html>
<head>
<title>Employee Details</title>
</head>
<body>
<basefont face="Arial">
<!-- JSP Declarations -->
<%! ResultSet rs = null; %>

<!-- JSP Scriptlet -->
<%
try {
Class.forName("org.gjt.mm.mysql.Driver");
Connection db = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/quoting");
Statement s = db.createStatement();
rs = s.executeQuery("select * from employee");
}
catch (Exception e) {
// For now, just report the error to the system log
System.out.println(e.toString());
}
%>
<!-- Template text -->
<table width="550" border="0" align="center">
<tr>
<td bgcolor="#006633">
<div align="center">
<font size="6" color="#FFFFFF">
<b>Employee Details</b>
</font>
</div>
</td>
</tr>
<tr>
<td>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p align="center"><b>Employees</b></p>
<table width="290" border="0" align="center">
<%
try {
while (rs.next()) {
%>
<!-- JSP Expressions used within template text -->
<tr>
<td width="20"><%= rs.getInt(1) %></td>
<td width="70"><%= rs.getString(2) %></td>
<td width="70"><%= rs.getString(3) %></td>
<td width="40">
<a href="emp.jsp?id=<%= rs.getString(1) %>&action=edit">
edit
</a>
</td>
<td width="40">
<a href="emp.jsp?id=<%= rs.getString(1) %>&action=delete">
delete
</a>
</td>
</tr>
<%
}
}
catch (SQLException e) {
// For now, just report the error to the system log
System.out.println(e.toString());
}
%>
</table>
</td>
</tr>
<tr>
<td>
<p>&nbsp;</p>
<p align="center"><a href="emp.jsp?action=add">New Employee</a></p>
</td>
</tr>
</table>
</body>
</html>

Output:

No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...