//Name: Aditya Patil
//Class: SYCO
//Roll No: 6
//Subject: Java programming
//Subject Code: 314317
//Practical Name:28. Write a program to implement following
operation on database insert record, update record , delete record
INPUT:
import java.sql.*;
public class DatabaseOperationsExample {
public static void main(String[] args) {
// Database credentials
String url = "jdbc:mysql://localhost:3306/sampleDB"; // Update with your
database name
String username = "root"; // Your MySQL username
String password = "password"; // Your MySQL password
// SQL Queries for Insert, Update, and Delete operations
String insertQuery = "INSERT INTO students (id, name, age) VALUES (?,
?, ?)";
String updateQuery = "UPDATE students SET name = ?, age = ? WHERE
id = ?";
String deleteQuery = "DELETE FROM students WHERE id = ?";
try (Connection conn = DriverManager.getConnection(url, username,
password)) {
System.out.println("Connected to MySQL successfully.");
// Insert a record into the students table
try (PreparedStatement insertStmt =
conn.prepareStatement(insertQuery)) {
insertStmt.setInt(1, 1); // Set id
insertStmt.setString(2, "Alice"); // Set name
insertStmt.setInt(3, 20); // Set age
int rowsAffected = insertStmt.executeUpdate();
System.out.println("Rows inserted: " + rowsAffected);
// Update a record in the students table
try (PreparedStatement updateStmt =
conn.prepareStatement(updateQuery)) {
updateStmt.setString(1, "Alice Johnson"); // Update name
updateStmt.setInt(2, 21); // Update age
updateStmt.setInt(3, 1); // Where id = 1
int rowsAffected = updateStmt.executeUpdate();
System.out.println("Rows updated: " + rowsAffected);
// Delete a record from the students table
try (PreparedStatement deleteStmt =
conn.prepareStatement(deleteQuery)) {
deleteStmt.setInt(1, 1); // Delete where id = 1
int rowsAffected = deleteStmt.executeUpdate();
System.out.println("Rows deleted: " + rowsAffected);
} catch (SQLException e) {
e.printStackTrace();
}
OUTPUT:
C:\java pro>javac DatabaseOperationsExample.java
C:\java pro>java DatabaseOperationsExample
Connected to MySQL successfully.
Rows inserted: 1
Rows updated: 1
Rows deleted: 1