杰瑞科技汇

Java executeUpdate如何返回受影响行数?

Of course! Let's dive deep into executeUpdate in Java, specifically in the context of JDBC (Java Database Connectivity).

Java executeUpdate如何返回受影响行数?-图1
(图片来源网络,侵删)

What is executeUpdate()?

In JDBC, executeUpdate() is a method of the java.sql.Statement interface (and its sub-interfaces, PreparedStatement and CallableStatement). Its primary purpose is to execute an SQL statement that modifies data in the database.

Key Characteristics:

  • Modifies Data: It's used for Data Manipulation Language (DML) statements like INSERT, UPDATE, and DELETE.
  • DDL Statements: It can also be used for Data Definition Language (DDL) statements like CREATE TABLE, ALTER TABLE, or DROP TABLE.
  • Returns an Integer: It returns an int value representing the number of rows that were affected (changed, inserted, or deleted) by the SQL statement.
  • Throws SQLException: If a database access error occurs, it throws a SQLException.

Method Signature

int executeUpdate(String sql) throws SQLException;
  • sql: A String containing the SQL command to be executed.
  • Return Value: The number of rows affected.

How to Use executeUpdate(): A Step-by-Step Example

Here is a complete, runnable example demonstrating how to use executeUpdate() with a standard Statement.

Prerequisites

  1. JDBC Driver: You need the JDBC driver for your specific database (e.g., PostgreSQL, MySQL, Oracle).
  2. Database Connection: A running database and the connection details (URL, username, password).

Example Code (Statement)

This example uses a Statement object. Important: This is vulnerable to SQL injection and should only be used with trusted input or for simple, static queries. For user input, always use PreparedStatement.

Java executeUpdate如何返回受影响行数?-图2
(图片来源网络,侵删)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class ExecuteUpdateExample {
    // --- Database Connection Details ---
    // IMPORTANT: Replace with your actual database details
    private static final String DB_URL = "jdbc:postgresql://localhost:5432/mydatabase";
    private static final String USER = "myuser";
    private static final String PASS = "mypassword";
    public static void main(String[] args) {
        // The try-with-resources statement ensures the connection is closed automatically.
        try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS)) {
            if (conn != null) {
                System.out.println("Connected to the database successfully!");
                // --- Example 1: INSERT ---
                System.out.println("\n--- Performing INSERT ---");
                String insertSql = "INSERT INTO employees (id, name, position, salary) VALUES (101, 'Alice', 'Developer', 75000)";
                int rowsInserted = executeUpdate(conn, insertSql);
                System.out.println(rowsInserted + " row(s) inserted.");
                // --- Example 2: UPDATE ---
                System.out.println("\n--- Performing UPDATE ---");
                String updateSql = "UPDATE employees SET salary = 80000 WHERE name = 'Alice'";
                int rowsUpdated = executeUpdate(conn, updateSql);
                System.out.println(rowsUpdated + " row(s) updated.");
                // --- Example 3: DELETE ---
                System.out.println("\n--- Performing DELETE ---");
                String deleteSql = "DELETE FROM employees WHERE id = 101";
                int rowsDeleted = executeUpdate(conn, deleteSql);
                System.out.println(rowsDeleted + " row(s) deleted.");
                // --- Example 4: DDL (CREATE TABLE) ---
                System.out.println("\n--- Performing DDL (CREATE TABLE) ---");
                String createTableSql = "CREATE TABLE IF NOT EXISTS projects (id INT PRIMARY KEY, name VARCHAR(100))";
                // For DDL, the return value is often 0, but it can vary by driver.
                int ddlResult = executeUpdate(conn, createTableSql);
                System.out.println("DDL executed. Return value: " + ddlResult);
            }
        } catch (SQLException e) {
            System.err.println("Database error: " + e.getMessage());
            e.printStackTrace();
        }
    }
    /**
     * A helper method to execute an SQL update statement.
     * @param conn The active database connection.
     * @param sql The SQL statement to execute.
     * @return The number of affected rows.
     * @throws SQLException if a database access error occurs.
     */
    private static int executeUpdate(Connection conn, String sql) throws SQLException {
        // The try-with-resources statement ensures the Statement is closed.
        try (Statement stmt = conn.createStatement()) {
            return stmt.executeUpdate(sql);
        }
    }
}

executeUpdate() vs. executeQuery() vs. execute()

This is a very common point of confusion for JDBC beginners. Here’s a simple breakdown:

Method Purpose Return Type Typical SQL Statement
executeUpdate() Executes a statement that modifies data. int (number of affected rows) INSERT, UPDATE, DELETE, CREATE, ALTER, DROP
executeQuery() Executes a statement that queries data and returns a single ResultSet. java.sql.ResultSet SELECT
execute() A general-purpose method that can run any type of SQL statement. boolean (true if a ResultSet is returned, false if an int is returned) Any SQL statement. Use when you don't know the type of query in advance.

Analogy:

  • executeQuery() is like asking a librarian for a list of books (SELECT). You expect a list back.
  • executeUpdate() is like telling the librarian to add a new book to the catalog (INSERT). You expect to know if the action was successful and how many books were affected.
  • execute() is like a Swiss Army knife. You can use it for anything, but it's more complex to use because you have to check what you got back.

PreparedStatement.executeUpdate() (The Recommended Approach)

For any query that takes user input, you should always use a PreparedStatement. It is more secure (prevents SQL injection) and often more efficient (the database can cache the execution plan).

Here's the same INSERT example using PreparedStatement:

Java executeUpdate如何返回受影响行数?-图3
(图片来源网络,侵删)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class PreparedStatementExample {
    private static final String DB_URL = "jdbc:postgresql://localhost:5432/mydatabase";
    private static final String USER = "myuser";
    private static final String PASS = "mypassword";
    public static void main(String[] args) {
        String insertSql = "INSERT INTO employees (id, name, position, salary) VALUES (?, ?, ?, ?)";
        try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
             // The PreparedStatement is created from the connection and the SQL query
             PreparedStatement pstmt = conn.prepareStatement(insertSql)) {
            // Set the parameters for the query using index (1-based)
            pstmt.setInt(1, 102);       // id
            pstmt.setString(2, "Bob");  // name
            pstmt.setString(3, "QA Engineer"); // position
            pstmt.setDouble(4, 65000.00); // salary
            // Execute the update
            int rowsAffected = pstmt.executeUpdate();
            System.out.println(rowsAffected + " row(s) inserted successfully.");
        } catch (SQLException e) {
            System.err.println("Database error: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

Key Takeaways

  1. Use executeUpdate() for DML (INSERT, UPDATE, DELETE) and DDL (CREATE, ALTER, DROP) statements.
  2. It returns an int representing the number of rows affected.
  3. For SELECT statements, you must use executeQuery().
  4. Always use PreparedStatement with executeUpdate() when your query includes variables or user input to prevent SQL injection and improve performance.
  5. Use try-with-resources to ensure that your Connection, Statement, and ResultSet objects are closed automatically, preventing resource leaks.
分享:
扫描分享到社交APP
上一篇
下一篇