Nicky
Nicky

Reputation: 63

How do I close() .executeUpdate?

I am wondering, how do I close an executeUpdate statement in JAVA(JDBC)?

For example:

String sql = "UPDATE. .. . ..  Whatever...";
ResultSet rs = stmt.executeQuery(sql);
rs.close();

But I couldn't do this to update. So I googled and found out that I need to use executeUpdate but how do I close the statement after?

String sql = "UPDATE. .. . ..  Whatever...";
int rs = stmt.executeUpdate(sql);
rs.close(); ??? <------

Upvotes: 1

Views: 2592

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074218

You don't close the executeUpdate, you close the Statement:

rs.close();   // Closes the ResultSet
stmt.close(); // Closes the Statement

Usually best to do that with a try-with-resources statement:

String sql = "UPDATE. .. . ..  Whatever...";
try (
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery(sql);
) {
    // Process results
}

try-with-resources will close both the Statement and the ResultSet for you. It was added in Java 7 (in 2011).


Side note: You've shown that you're using Statement and calling executeUpdate(String). That's fine as long as there's no externally-sourced information in the SQL (nothing you've received from user input or another system, etc.). In the more common case, though, you'd want to use a PreparedStatement, call setXyz to set parameters, and then call executeUpdate() (the zero-args version). This habit keeps you safe from SQL injection. More explanation and examples on this useful site: http://bobby-tables.com/.

Upvotes: 6

STaefi
STaefi

Reputation: 4377

Most of the times when you are updating a table you don't get a ResultSet as the result, So no need to close the ResultSet.

Just close the Statement.

Upvotes: 1

Related Questions