Updating Data using JDBC
Using Statement:
Statement is suitable for executing simple SQL queries without parameters.
Steps to Execute an UPDATE 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 UPDATE query using the Statement.
Example Code using Statement (Java):
Using PreparedStatement:
PreparedStatement is used for executing parameterized SQL queries.
Steps to Execute an UPDATE 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:
StatementUpdateExample: Uses
Statement
to update the age of the user with ID 1 to 35.PreparedStatementUpdateExample: Uses
PreparedStatement
to update the age of the user with a specific ID. Parameters (?) are used for values that will be replaced during execution, providing protection against SQL Injection.
Last updated