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):
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class StatementUpdateExample {
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 = "UPDATE users SET age = 35 WHERE id = 1";
int rowsAffected = statement.executeUpdate(sqlQuery);
if (rowsAffected > 0) {
System.out.println("Data updated successfully!");
} else {
System.out.println("Failed to update data.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
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):
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class PreparedStatementUpdateExample {
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 = "UPDATE users SET age = ? WHERE id = ?";
int newAge = 40;
int userId = 2;
try (PreparedStatement preparedStatement = connection.prepareStatement(sqlQuery)) {
preparedStatement.setInt(1, newAge);
preparedStatement.setInt(2, userId);
int rowsAffected = preparedStatement.executeUpdate();
if (rowsAffected > 0) {
System.out.println("Data updated successfully!");
} else {
System.out.println("Failed to update data.");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
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