Deleting Data using JDBC
Using Statement:
Statement is suitable for executing simple SQL queries without parameters.
Steps to Execute a DELETE Query Using Statement:
Establish a Connection: Establish a connection to the database.
Create a Statement: Create a Statement object using the connection.
Execute Query: Execute the SQL DELETE query using the Statement.
Example Code using Statement (Java):
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class StatementDeleteExample {
public static void main(String[] args) {
String jdbcUrl = "jdbc:mysql://localhost:3306/mydatabase";
String username = "username";
String password = "password";
try (Connection connection = DriverManager.getConnection(jdbcUrl, username, password);
Statement statement = connection.createStatement()) {
String sqlQuery = "DELETE FROM users WHERE id = 1";
int rowsAffected = statement.executeUpdate(sqlQuery);
if (rowsAffected > 0) {
System.out.println("Data deleted successfully!");
} else {
System.out.println("Failed to delete data.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Using PreparedStatement:
PreparedStatement is used for executing parameterized SQL queries.
Steps to Execute a DELETE Query Using PreparedStatement:
Establish a Connection: Establish a connection to the database.
Create a PreparedStatement: Create a PreparedStatement object with the parameterized query using the connection.
Set Parameters: Set the parameter values using setter methods of the PreparedStatement.
Execute Query: Execute the PreparedStatement.
Example Code using PreparedStatement (Java):
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class PreparedStatementDeleteExample {
public static void main(String[] args) {
String jdbcUrl = "jdbc:mysql://localhost:3306/mydatabase";
String username = "username";
String password = "password";
try (Connection connection = DriverManager.getConnection(jdbcUrl, username, password)) {
String sqlQuery = "DELETE FROM users WHERE id = ?";
int userId = 2;
try (PreparedStatement preparedStatement = connection.prepareStatement(sqlQuery)) {
preparedStatement.setInt(1, userId);
int rowsAffected = preparedStatement.executeUpdate();
if (rowsAffected > 0) {
System.out.println("Data deleted successfully!");
} else {
System.out.println("Failed to delete data.");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Explanation:
StatementDeleteExample: Uses
Statement
to delete the user with ID 1 from theusers
table.PreparedStatementDeleteExample: Uses
PreparedStatement
to delete the user with a specific ID from theusers
table. Parameters (?) are used for values that will be replaced during execution, providing protection against SQL Injection.
Last updated