15. Write a java program to demonstrate the usage of JDBC in performing various DML statements using prepared statements.

PHOTO EMBED

Sat Nov 16 2024 00:26:30 GMT+0000 (Coordinated Universal Time)

Saved by @webtechnologies

import java.sql.*;

public class DMLExamples {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/your_database";
        String username = "root";
        String password = "your_password";

        try (Connection connection = DriverManager.getConnection(url, username, password)) {
            System.out.println("Connected to the database.");

          
            String insertSQL = "INSERT INTO your_table (column1, column2) VALUES (?, ?)";
            try (PreparedStatement insertStmt = connection.prepareStatement(insertSQL)) {
                insertStmt.setString(1, "Alice");
                insertStmt.setInt(2, 30);
                int rowsInserted = insertStmt.executeUpdate();
                System.out.println(rowsInserted + " row(s) inserted.");
            }

            
            String updateSQL = "UPDATE your_table SET column2 = ? WHERE column1 = ?";
            try (PreparedStatement updateStmt = connection.prepareStatement(updateSQL)) {
                updateStmt.setInt(1, 35); // New value for column2
                updateStmt.setString(2, "Alice"); // Condition
                int rowsUpdated = updateStmt.executeUpdate();
                System.out.println(rowsUpdated + " row(s) updated.");
            }

          
            String selectSQL = "SELECT * FROM your_table";
            try (PreparedStatement selectStmt = connection.prepareStatement(selectSQL)) {
                ResultSet resultSet = selectStmt.executeQuery();
                System.out.println("Data in the table:");
                while (resultSet.next()) {
                    int id = resultSet.getInt("id");
                    String column1 = resultSet.getString("column1");
                    int column2 = resultSet.getInt("column2");
                    System.out.printf("ID: %d, Column1: %s, Column2: %d%n", id, column1, column2);
                }
            }

          
            String deleteSQL = "DELETE FROM your_table WHERE column1 = ?";
            try (PreparedStatement deleteStmt = connection.prepareStatement(deleteSQL)) {
                deleteStmt.setString(1, "Alice");
                int rowsDeleted = deleteStmt.executeUpdate();
                System.out.println(rowsDeleted + " row(s) deleted.");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
content_copyCOPY