开发者

When to close Statement when using jdbc

开发者 https://www.devze.com 2023-04-05 06:33 出处:网络
I am using odbc to connect mysql database in Java I write a function \"ExecuteQuery\", it takes a string parameter as sql statemen开发者_如何转开发t and returns its resultset. However, when should I

I am using odbc to connect mysql database in Java

I write a function "ExecuteQuery", it takes a string parameter as sql statemen开发者_如何转开发t 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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号