📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
In this guide, you will learn about the Statement executeUpdate() method in Java programming and how to use it with an example.
1. Statement executeUpdate() Method Overview
Definition:
The executeUpdate() method of the Statement interface is used to execute DDL(Data Definition Language) statements, such as CREATE, DROP, ALTER and DML(Data Manipulation Language) statements like INSERT, UPDATE, DELETE, etc. It returns an integer representing the number of rows affected by the SQL statement.
Syntax:
int executeUpdate(String sql) throws SQLException
Parameters:
- sql: a String object that is the SQL statement to be sent to the database.
Key Points:
- The executeUpdate() method is used for executing SQL statements that change the database in some way, i.e., the statements that are used to create, modify, delete or update data.
- The method returns the row count for SQL Data Manipulation Language (DML) statements or 0 for SQL statements that return nothing.
- The method throws a SQLException if a database access error occurs, the given SQL statement produces a ResultSet object, or the method is called on a closed Statement.
2. Statement executeUpdate() Method Example
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.SQLException;
public class ExecuteUpdateExample {
public static void main(String[] args) {
String url = "jdbc:your_database_url";
String user = "your_database_user";
String password = "your_database_password";
String updateSql = "UPDATE employees SET salary = 50000 WHERE last_name = 'Doe'";
try (Connection connection = DriverManager.getConnection(url, user, password);
Statement statement = connection.createStatement()) {
int rowsAffected = statement.executeUpdate(updateSql);
System.out.println("Rows affected: " + rowsAffected);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Output:
Rows affected: [Number of rows updated]
Explanation:
In this example, a connection to the database is established, and the executeUpdate() method is called with an SQL UPDATE statement as its parameter.
The executeUpdate() method returns an integer representing the number of rows affected by the execution of the SQL statement, which is then printed to the console. If any SQLException occurs during this process, it is caught and printed to the console.
Comments
Post a Comment
Leave Comment