Java_Practical
Java_Practical
Practical-1
Aim: Write down basic steps to establish database connection from java. Also
write the connection code for different db.
Basic Steps to Establish a Database Connection in Java:
1. Load the JDBC Driver: This is required to use the JDBC API for database
communication.
2. Establish a Connection: Using DriverManager.getConnection() with
appropriate credentials (URL, username, password).
3. Create a Statement: To execute SQL queries using Statement,
PreparedStatement, or CallableStatement.
4. Execute the Query: Perform database operations like SELECT, INSERT,
UPDATE, or DELETE.
5. Process the ResultSet (if applicable): Fetch and process data retrieved
from the database.
6. Close the Connection: Always close ResultSet, Statement, and
Connection to free resources.
1
IU2241230188 Advance Java(AJT) 6CSE-E
Code:
import java.sql.*; public class SQLConnection { public static void main(String[] args) { String
url = "jdbc:mysql://localhost:3306/mysql"; String user = "root"; String password = "root"; try
{ Class.forName("com.mysql.cj.jdbc.Driver"); Connection con =
DriverManager.getConnection(url, user, password); System.out.println("Connected to SQL
Server successfully!"); con.close(); } catch (Exception e) { e.printStackTrace(); } } }
2
IU2241230188 Advance Java(AJT) 6CSE-E
Practical-2
Aim: Users can create a new database and also create a new table under that database.
Once a database has been created then the user can perform database operation by calling
above functions. Use following Java Statement interface to implement program: 1.Statement
2.Preparedstatement 3.Callablestatement Write a JDBC application which will perform CRUD
operation on the Student table
InsertData
Code:
package DB;import java.sql.*;import java.util.Scanner;
String query = "INSERT INTO student VALUES (" + sid + ", '" + sname + "', '" + saddr + "', '" + gender +
"', '" + gmail + "', '" + course + "', '" + dob + "', '" + phone + "')";
s.execute(query);System.out.println("Data inserted successfully!"); s.close();con.close(); } catch
(SQLException err) {System.out.println("ERROR: " + err);} catch (Exception err) {
3
IU2241230188 Advance Java(AJT) 6CSE-E
UpdateData
import java.sql.*; import java.util.Scanner; public class UpdateData { public static void
main(String[] args) { try { Class.forName("org.apache.derby.jdbc.ClientDriver"); Connection
con = DriverManager.getConnection("jdbc:derby://localhost:1527/students", "root", "root");
Statement s = con.createStatement(); Scanner sc = new Scanner(System.in);
System.out.println("Update Data in student table : ");
System.out.println("________________________________________");
System.out.print("Enter Student ID: "); int sid = sc.nextInt(); sc.nextLine();
System.out.print("Enter Student Name: "); String sname = sc.nextLine();
System.out.print("Enter Student Address: "); String saddr =
sc.nextLine();System.out.print("Enter Gender: "); String gender = sc.next(); sc.nextLine();
System.out.print("Enter Gmail: "); String gmail = sc.nextLine(); System.out.print("Enter
Course: ");String course = sc.nextLine();System.out.print("Enter Date of Birth (YYYY-MM-DD):
");String dob = sc.next(); sc.nextLine();System.out.print("Enter Phone Number: "); String
4
IU2241230188 Advance Java(AJT) 6CSE-E
+ "', gmail='" + gmail + "', course='" + course + "', dob='" + dob + "', phone_no='" + phone + "'
WHERE s_id=" +sid;s.execute(query); System.out.println("Data updated successfully!");
s.close(); con.close();} catch (SQLException err) { System.out.println("ERROR: " + err); } catch
(Exception err) { System.out.println("ERROR: " + err); }} }
Output:
Delete
package DB; import java.sql.*; import java.util.Scanner; public class DeleteData { public static
void main(String[] args) { try { Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/students",
"root", "root"); Statement s = con.createStatement(); Scanner sc = new Scanner(System.in);
System.out.println("Delete Data from student table : "); System.out.print("Enter Student ID:
"); int sid = sc.nextInt(); String query = "DELETE FROM student WHERE s_id=" + sid;
s.execute(query); System.out.println("Data deleted successfully!"); s.close(); con.close(); }
catch (SQLException err) { System.out.println("ERROR: " + err); } catch (Exception err) {
System.out.println("ERROR: " + err); } } }
Output:
5
IU2241230188 Advance Java(AJT) 6CSE-E
Display:
package DB; import java.sql.*; import java.util.Scanner; public class DisplayData { public
static void main(String[] args) { try { Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/students",
"root", "root"); Statement s = con.createStatement(); ResultSet rs = s.executeQuery("SELECT
* FROM student"); Scanner sc = new Scanner(System.in); while (rs.next()) {
System.out.println("Student ID : " + rs.getInt("s_id")); System.out.println("Name : " +
rs.getString("s_name")); System.out.println("Address : " + rs.getString("s_address"));
System.out.println("Gender : " + rs.getString("gender")); System.out.println("Gmail : " +
rs.getString("gmail")); System.out.println("Course : " +
rs.getString("course"));System.out.println("Date of Birth : " + rs.getString("dob"));
System.out.println("Phone No : " + rs.getString("phone_no")); System.out.print("Press Enter
to view the next record..."); sc.nextLine(); } s.close(); con.close(); sc.close(); } catch
(Exception err) { System.out.println("ERROR: " + err); } } }
Output:
6
IU2241230188 Advance Java(AJT) 6CSE-E
Pracitical-3
Aim: Write a JDBC application to display records from the database using metadata.
Code:
package DB; import java.sql.*; public class JD { public static void main(String[] args) { String DB_URL =
"jdbc:mysql://localhost:3306/employeesdb"; String USER = "root”; String PASSWORD = "root"; String QUERY =
"SELECT * FROM employees"; try { Class.forName("com.mysql.cj.jdbc.Driver");Connection conn =
DriverManager.getConnection(DB_URL, USER, PASSWORD); Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(QUERY); ResultSetMetaData metaData = rs.getMetaData(); int columnCount
= metaData.getColumnCount(); System.out.println("Table Columns:"); for (int i = 1; i <= columnCount; i++) {
System.out.print(metaData.getColumnName(i) + "\t"); } System.out.println("\n-------------------------------------------
------"); while (rs.next()) { for (int i = 1; i <= columnCount; i++) { System.out.print(rs.getString(i) + "\t"); }
System.out.println(); } rs.close(); stmt.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } } }
Output:
7
IU2241230188 Advance Java(AJT) 6CSE-E
Practical-4
Aim: Create a web application for servlet and study web descriptor files. Write a servlet code which
performs servletcontext and servletconfig object.
Creating a Web Application for Servlet and Studying Web Descriptor Files.
In a basic Java web application using Servlets, we use web.xml (web descriptor file) for configuration.
Below is a simple servlet program demonstrating the use of ServletContext and ServletConfig
objects.
5. Click Finish.
CODE:
Web.xml
8
IU2241230188 Advance Java(AJT) 6CSE-E
Code:
public class Servlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException { response.setContentType("text/html"); PrintWriter out =
response.getWriter(); ServletConfig config = getServletConfig(); String configParam =
config.getInitParameter("configParam"); ServletContext context = getServletContext(); String
contextParam = context.getInitParameter("contextParam"); out.println("<html><body>");
out.println("<h2>Using ServletConfig and ServletContext</h2>"); out.println("<p>ServletConfig
Parameter: " + configParam + "</p>"); out.println("</p>ServletContext Parameter: " + contextParam
+ "</p>"); out.println("</body></html>"); } }
Output
9
IU2241230188 Advance Java(AJT) 6CSE-E
Practical-5
Aim: : Implement login form and perform session management using different methods.
Code:
Output:
Code:
10
IU2241230188 Advance Java(AJT) 6CSE-E
Code:
Output:
11
IU2241230188 Advance Java(AJT) 6CSE-E
Practical-6
Aim: Develop a web application for a bank system which performs the
following task. 1.Create database and master table for bank 2.Perform insert,
update and delete operation. 3.Validate the attributes.
12
IU2241230188 Advance Java(AJT) 6CSE-E
Output:
13
IU2241230188 Advance Java(AJT) 6CSE-E
14
IU2241230188 Advance Java(AJT) 6CSE-E
Practical-7
Aim: Write down the program for testing the include action and forward action
for servlet collaboration.
HeaderServlet.java (Include Action)
import java.io.*;import javax.servlet.*;@WebServlet("/HeaderServlet")public class
HeaderServlet extends HttpServlet {protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {PrintWriter out =
response.getWriter();out.println("<h1>My Web App</h1><hr>");}}
15
IU2241230188 Advance Java(AJT) 6CSE-E
Output:
16
IU2241230188 Advance Java(AJT) 6CSE-E
Practical-8
Aim: Write down the program for testing the include and forward
action tag in jsp.
index.jsp (Main Page with Include & Forward Actions)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %><%@ page
import="javax.servlet.http.HttpSession" %><%String user = (String) session.getAttribute("user");%><!DOCTYPE
html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,
initial-scale=1.0"><title>Include & Forward Example</title><style>body { font-family: Arial, sans-serif; text-align:
center; }.hidden { display: none; }.container { padding: 20px; border: 1px solid #ddd; width: 300px; margin: auto;
}</style></head><body><!-- Include Action: Common Header --><jsp:include page="header.jsp" /><% if (user ==
null) { %> <!-- Page 1: Login --><div id="page1" class="container"><h2>Login Page</h2><form action="login.jsp"
method="post"><input type="text" name="username" placeholder="Enter Username"><br><br><button
type="submit">Login</button></form></div><% } else { %><!-- Page 2: Welcome --><div id="page2"
class="container"><h2>Welcome!</h2><p>Hello, <%= user %>!</p><form action="logout.jsp"
method="post"><button type="submit">Logout</button></form> </div> <% } %></body></html>
Output:
17
IU2241230188 Advance Java(AJT) 6CSE-E
18