Reputation: 153
I am not sure, which method is better?
con.createStatement().execute("...");
OR
Statement st = con.createStatement();
st.execute("...");
st.close();
When using the first method, will be the statement create closed or it will remain open? I am sure that in the second method the statement will be closed, but in the first one? Anybody know?
Upvotes: 1
Views: 2860
Reputation: 108971
Neither is good, although the second alternative is better than the first. You should always close a statement when you are done with (not sooner, but definitely not never). Your second alternative attempts to close the statement, but will actually fail to do that if execute
throws an exception.
To have a guaranteed close of your statement, you can use try-with-resource (introduced in Java 7):
try (Statement statement = connection.createStatement) {
statement.execute();
// Other things you want to with statement...
}
If you are unfortunate to be stuck on Java 6 or earlier, you need to use a try/finally:
Statement statement = connection.createStatement();
try {
statement.execute();
// Other things you want to with statement...
} finally {
statement.close();
}
Upvotes: 2
Reputation: 1905
Both con.createStatement().execute("...");
and Statement st = con.createStatement();
make same sense. However closing the statement is not performed with the first method. Closing the ResultSet
or Statement
is a good practice. You may get additional problems with not closed Statements
. You can close the Connection
instead, but it's not possible when using a connection pool. Additionally the second method is very useful when using the PrepairedStatement
, because it can set parameters to the PreparedStatement
.
Upvotes: 0
Reputation: 180161
If you do not explicitly close the Statement
object then it will remain open, at least initially. It might be closed some time after the garbage collector determines that it is unreachable, if ever that happens. It will be closed when the connection is closed, if at that time it is still open.
The best form is usually:
Statement st = con.createStatement();
try {
// ...
st.execute("...");
// ...
} finally {
st.close();
}
By starting a try
block immediately after creating a statement, you can be sure that the statement will be closed (in the finally
block) before it goes out of scope -- even if an arbitrary exception is thrown somewhere within.
Upvotes: 1
Reputation: 311188
In the first snippets, you are not explicitly closing the statement, so you can not rely on it being closed. Some driver's implementations call close()
in the statement's finalize()
method, but you should not rely on this, and should always explicitly close your statements.
Upvotes: 0