23695A0526 Web 2
23695A0526 Web 2
Pavaneswar Reddy
REG ᅠ NO 23695A0526
ASSIGNMENT II
SET ᅠ NO 6
The first step is to load the JDBC driver for the database. In JSP, you typically use the
Class.forName() method to load the driver.
Example:
<%@ page import="java.sql.*" %>
<%
try {
// Load the JDBC driver for MySQL
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
out.println("Driver not found: " + e.getMessage());
}
%>
Step 2: Establish Database Connection
Once the JDBC driver is loaded, you can establish a connection to the database
using the DriverManager.getConnection() method. This method requires a
connection string, username, and password.
Example:
<%
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/mydatabase"; // Database URL
String username = "root"; // Database username
String password = "password"; // Database password
try {
conn = DriverManager.getConnection(url, username, password);
out.println("Connection successful!");
} catch (SQLException e) {
out.println("Connection failed: " + e.getMessage());
}
%>
Step 3: Create a Statement and Execute Queries
Once the connection is established, you can create a Statement object and
execute queries to interact with the database.
Example (retrieving data from a table):
<%
String query = "SELECT * FROM employees"; // Sample SQL query
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(query);