JSP Database
Fri Nov 15 2024 19:01:18 GMT+0000 (Coordinated Universal Time)
Saved by @signup_returns
<%@ page import="java.sql.*" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>JSP Oracle Database Connectivity</title>
<style>
table { width: 60%; margin: 20px auto; border-collapse: collapse; }
table, th, td { border: 1px solid black; text-align: center; padding: 8px; }
th { background-color: #f2f2f2; }
h2 { text-align: center; }
</style>
</head>
<body>
<h2>User Details from Oracle Database</h2>
<%
// Oracle database connection details
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String username = "system"; // Replace with your Oracle username
String password = "1234"; // Replace with your Oracle password
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Load the Oracle JDBC driver
//Class.forName("oracle.jdbc.driver.OracleDriver");
// Establish the database connection
conn = DriverManager.getConnection(url, username, password);
// Create a statement object to execute queries
stmt = conn.createStatement();
// Execute a query to fetch data from the 'users' table
String query = "SELECT * FROM users";
rs = stmt.executeQuery(query);
%>
<table>
<tr>
<th>User ID</th>
<th>Name</th>
<th>Email</th>
</tr>
<%
// Iterate through the result set and display data in the table
while (rs.next()) {
%>
<tr>
<td><%= rs.getInt("user_id") %></td>
<td><%= rs.getString("name") %></td>
<td><%= rs.getString("email") %></td>
</tr>
<%
}
%>
</table>
<%
} catch (Exception e) {
out.println("<p style='color:red; text-align:center;'>Error: " + e.getMessage() + "</p>");
} finally {
// Close all resources to avoid memory leaks
if (rs != null) try { rs.close(); } catch (SQLException ignored) {}
if (stmt != null) try { stmt.close(); } catch (SQLException ignored) {}
if (conn != null) try { conn.close(); } catch (SQLException ignored) {}
}
%>
</body>
</html>



Comments