How do you Connect to the Database From JSP

A Connection to a database can be established from a jsp page by writing the code to establish a connection using a jsp scriptlets.

Further then you can use the resultset object “res” to read data in the following way.

In advanced Java web development, connecting to a database from JSP (JavaServer Pages) directly is not considered a good practice. It is recommended to follow a layered architecture where database connectivity and business logic are separated. Commonly, a combination of servlets and JavaBeans is used for database connectivity in conjunction with JSP for presentation.

However, if you are looking for a basic example of how to establish a database connection within a JSP page, you can use Java code embedded within the JSP, but it is not recommended for production code due to security and maintainability concerns. Here’s an example:

jsp
<%@ page import="java.sql.*" %>
<%@ page import="javax.naming.*" %>
<%@ page import="javax.sql.*" %>
<%@ page contentType=“text/html;charset=UTF-8” language=“java” %>
<html>
<head>
<title>Database Connection Example</title>
</head>
<body>
<%
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;

try {
// Load the JDBC driver
Class.forName(“your.database.driver.ClassName”);

// Establish the connection
connection = DriverManager.getConnection(“jdbc:your_database_connection_url”, “username”, “password”);

// Create a statement
statement = connection.createStatement();

// Execute a query
resultSet = statement.executeQuery(“SELECT * FROM your_table”);

// Process the result set
while (resultSet.next()) {
// Retrieve data from the result set
String data = resultSet.getString(“column_name”);
// Process data as needed
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Close resources in the reverse order of their creation
if (resultSet != null) {
try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); }
}
if (statement != null) {
try { statement.close(); } catch (SQLException e) { e.printStackTrace(); }
}
if (connection != null) {
try { connection.close(); } catch (SQLException e) { e.printStackTrace(); }
}
}
%>
</body>
</html>

Replace "your.database.driver.ClassName", "jdbc:your_database_connection_url", "username", "password", "your_table", and "column_name" with your actual database driver class name, connection URL, username, password, table name, and column name.

Note: This example is for educational purposes only, and using JSP for database connectivity is not recommended in modern web application development. Consider using servlets, JavaBeans, and frameworks like JavaServer Faces (JSF) or Spring for a more robust and maintainable solution.