Write a Java Program to delete details of students whose initial character of their name is ‘S’.
Answer
import java.sql.*;
public class DeleteStudentJDBC {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/college";
String user = "root";
String password = "root";
try {
// Load JDBC Driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Establish Connection
Connection con = DriverManager.getConnection(url, user, password);
// SQL query to delete students whose name starts with 'S'
String sql = "DELETE FROM student WHERE name LIKE 'S%'";
Statement stmt = con.createStatement();
int rowsDeleted = stmt.executeUpdate(sql);
System.out.println(rowsDeleted + " student record(s) deleted successfully.");
// Close resources
stmt.close();
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
SQL Query
CREATE TABLE student (
rollno INT PRIMARY KEY,
name VARCHAR(50),
course VARCHAR(50)
);
Sample Data
INSERT INTO student VALUES
(1, ‘Sanjay’, ‘BCA’),
(2, ‘Amit’, ‘BCA’),
(3, ‘Sunita’, ‘BCA’),
(4, ‘Rahul’, ‘BCA’),
(5, ‘Seema’, ‘BCA’);