Database Connectivity using JSP

PHOTO EMBED

Sat Nov 16 2024 04:12:46 GMT+0000 (Coordinated Universal Time)

Saved by @wtlab

 <%@ page language="java" contentType="text/html; charset=UTF-8" 
pageEncoding="UTF-8"%>
<%@ page import="java.sql.Connection, java.sql.DriverManager, 
java.sql.PreparedStatement, java.sql.ResultSet" %>
<!DOCTYPE html>
<html>
<head>
 <title>Database Connectivity Example</title>
</head>
<body>
 <h2>User List</h2>
 <%
 // Database credentials
 String jdbcUrl = "jdbc:mysql://localhost:3306/mydb";
 String jdbcUsername = "root"; // replace with your database username
 String jdbcPassword = "password"; // replace with your database password
 
 // Database connection and query execution
 Connection conn = null;
 PreparedStatement stmt = null;
 ResultSet rs = null;
 
 try {
 
 Class.forName("com.mysql.cj.jdbc.Driver");
 
 conn = DriverManager.getConnection(jdbcUrl, jdbcUsername, jdbcPassword);
   // Prepare SQL query
 String sql = "SELECT * FROM users";
 stmt = conn.prepareStatement(sql);
 
 // Execute query
 rs = stmt.executeQuery();
 
 // Display results
 %>
 <table border="1">
 <tr>
 <th>ID</th>
 <th>Name</th>
 <th>Email</th>
 </tr>
 <%
 while (rs.next()) {
 %>
 <tr>
 <td><%= rs.getInt("id") %></td>
 <td><%= rs.getString("name") %></td>
 <td><%= rs.getString("email") %></td>
 </tr>
 <%
 }
 %>
 </table>
 <%
   } catch (Exception e) {
 out.println("Database connection error: " + e.getMessage());
 }
finally { 
 if (rs != null) 
try { 
rs.close();
} 
catch (Exception e) { }
 if (stmt != null) 
try { stmt.close();
} 
catch (Exception e) { /* ignored */ }
 if (conn != null)
try {
conn.close();
} 
catch (Exception e) { /* ignored */ }
 }
 %>
</body>
</html>
content_copyCOPY