Experiment 12
Experiment 12
Problem Statement:
Write a Java program for Database connectivity with MySQL.
Conclusion: This experiment helps the students to understand the concept of Java
Database connectivity (JDBC).
Code:
<%@ page import="java.sql.*" %>
<html>
<head>
<title>Display User Info</title>
</head>
<body>
<!-- Create a form with a button to trigger the data retrieval
--> <form method="post">
<input type="submit" value="Click Me">
</form>
<%
// This block will execute when the form is submitted (via
POST method) if
(request.getMethod().equalsIgnoreCase("POST")) { %>
<table border="1">
<tr>
<th>ID</th>
<th>Username</th>
<th>email</th>
</tr>
<%
// JDBC URL, username, and password of MySQL server
String jdbcUrl = "jdbc:mysql://localhost:3306/conn";
String jdbcUser = "root";
String jdbcPassword = "root";
// Declare JDBC objects
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Load the MySQL JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Establish the connection
conn = DriverManager.getConnection(jdbcUrl, jdbcUser,
jdbcPassword); // Create a statement
stmt = conn.createStatement();
// Execute a query to retrieve data
String sql = "SELECT * FROM userInfo";
rs = stmt.executeQuery(sql);
// Process the result set and display data in input text boxes
while (rs.next()) {
int id = rs.getInt("id");
String username = rs.getString("username");
String password = rs.getString("email");
// Output user data in text boxes
%>
<tr>
<td><input type="text" name="id" value="<%= id %>" readonly></td>
<td><input type="text" name="username" value="<%= username %>"
readonly></td>
<td><input type="text" name="password" value="<%= password %>"
readonly></td>
</tr>
<%
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Close JDBC resources
if (rs != null) try { rs.close(); } catch (SQLException e) {
e.printStackTrace(); } if (stmt != null) try { stmt.close(); } catch
(SQLException e) {
e.printStackTrace(); }
if (conn != null) try { conn.close(); } catch (SQLException e) {
e.printStackTrace(); }
}
%>
</table>
<%
} // End of form submission check
%>
</body>
</html>
Hamza Selanawala
SY\I.T.\B\37