11.Perform Database Access through JSP.
--------------------------------------------------------------
Database Setup (MySQL)
CREATE DATABASE studentdb;
USE studentdb;
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
course VARCHAR(100)
);
INSERT INTO students (name, course) VALUES
('Ravi', 'Java'),
('Priya', 'Python'),
('Anil', 'Data Science');
-----------------------------------------
JSP File (dbaccess.jsp)
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<title>Database Access Example</title>
</head>
<body>
<h2>Student Records from MySQL Database</h2>
<%
// JDBC connection details
String url = "jdbc:mysql://localhost:3306/studentdb";
String user = "root"; // change to your MySQL username
String pass = "root"; // change to your MySQL password
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Load MySQL JDBC Driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Establish connection
conn = DriverManager.getConnection(url, user, pass);
// Create statement and execute query
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM students");
%>
<table border="1" cellpadding="8">
<tr>
<th>ID</th>
<th>Name</th>
<th>Course</th>
</tr>
<%
// Loop through results
while(rs.next()) {
%>
<tr>
<td><%= rs.getInt("id") %></td>
<td><%= rs.getString("name") %></td>
<td><%= rs.getString("course") %></td>
</tr>
<%
}
%>
</table>
<%
} catch(Exception e) {
out.println("<p style='color:red;'>Error: " + e.getMessage() + "</p>");
} finally {
try { if(rs != null) rs.close(); } catch(Exception e) {}
try { if(stmt != null) stmt.close(); } catch(Exception e) {}
try { if(conn != null) conn.close(); } catch(Exception e) {}
}
%>
</body>
</html>
--------------------------------