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):
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):
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