10. Write a Java program to throw the SQL Query, insert, delete, update, if not successful then throw an exception
💡Code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DatabaseOperationExample {
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/your_database";
private static final String USERNAME = "your_username";
private static final String PASSWORD = "your_password";
public static void main(String[] args) {
try {
// Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Establish a connection
Connection connection = DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD);
// Example: Insert operation
insertData(connection, "John Doe", 25);
// Example: Update operation
updateData(connection, 1, "Jane Doe", 30);
// Example: Delete operation
deleteData(connection, 2);
// Close the connection
connection.close();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
private static void insertData(Connection connection, String name, int age) throws SQLException {
String insertQuery = "INSERT INTO your_table (name, age) VALUES (?, ?)";
try (PreparedStatement preparedStatement = connection.prepareStatement(insertQuery)) {
preparedStatement.setString(1, name);
preparedStatement.setInt(2, age);
// Execute the query
int rowsAffected = preparedStatement.executeUpdate();
// Check if the operation was successful
if (rowsAffected <= 0) {
throw new SQLException("Insert operation failed.");
} else {
System.out.println("Insert operation successful.");
}
}
}
private static void updateData(Connection connection, int id, String name, int age) throws SQLException {
String updateQuery = "UPDATE your_table SET name = ?, age = ? WHERE id = ?";
try (PreparedStatement preparedStatement = connection.prepareStatement(updateQuery)) {
preparedStatement.setString(1, name);
preparedStatement.setInt(2, age);
preparedStatement.setInt(3, id);
// Execute the query
int rowsAffected = preparedStatement.executeUpdate();
// Check if the operation was successful
if (rowsAffected <= 0) {
throw new SQLException("Update operation failed.");
} else {
System.out.println("Update operation successful.");
}
}
}
private static void deleteData(Connection connection, int id) throws SQLException {
String deleteQuery = "DELETE FROM your_table WHERE id = ?";
try (PreparedStatement preparedStatement = connection.prepareStatement(deleteQuery)) {
preparedStatement.setInt(1, id);
// Execute the query
int rowsAffected = preparedStatement.executeUpdate();
// Check if the operation was successful
if (rowsAffected <= 0) {
throw new SQLException("Delete operation failed.");
} else {
System.out.println("Delete operation successful.");
}
}
}
}
📸Output :