Bear
Bear

Reputation: 5152

When to close Statement when using jdbc

I am using odbc to connect mysql database in Java

I write a function "ExecuteQuery", it takes a string parameter as sql statement and returns its resultset. However, when should I close the statement object? If I close it in function ExecuteQuery, the returned resultset will be closed as well. If I don't close it, memory leak occurs as I do not have the reference of statement object in caller. Thank you

Upvotes: 0

Views: 142

Answers (1)

Alex Abdugafarov
Alex Abdugafarov

Reputation: 6412

You're taking wrong approach. If you really need such function (which is doubtful), make it accept a Statement as a parameter and make a separate function to create and set up that statement. Then you may wrap your function and ResultSet work in a try..finally block and close the statement in finally.

E.g.

Statement statement = getStatement();
try {
    ResultSet rs = executeQuery(statement, query);
    ...
} finally {
    statement.close();
}

However, if you're facing such problems, you may want to re-consider your architecture. Take a look at Hibernate, for example.

Upvotes: 3

Related Questions