The JDBC Update Operation is used to modify existing records in a database table. It is commonly performed using SQL UPDATE statements through JDBC APIs.
executeUpdate()Statement and PreparedStatementThe SQL syntax for update operation:
UPDATE table_name SET column1 = value1 WHERE condition;
// JDBC program to update student record
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class UpdateExample {
public static void main(String[] args) {
try {
// Load JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Create connection
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/college","root","password");
// Create statement
Statement stmt = con.createStatement();
// Execute update query
int rows = stmt.executeUpdate(
"UPDATE student SET marks=85 WHERE id=1");
// Display affected rows
System.out.println(rows + " record updated");
// Close connection
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
1 record updated
The output indicates how many rows were affected by the update query. If the condition does not match, the result will be 0.
| ID | Name | Marks |
|---|---|---|
| 101 | Alice Johnson | 70 |
| 102 | Bob Smith | 88 |
WHERE clause to avoid updating all recordsPreparedStatement to prevent SQL InjectionPreparedStatement instead of Statement