What are the best practices for Java – JDBC connections / result sets / statements
•
Java
I want to know what is the best practice in the following code snippet. Do I have to close all stmt and RS every time I complete executeQuery in each 'if', or can I do so now, close RS and stmt at the end of runonsqlserver and close the connection method at the end? Thank you for any instructions!
public void runOnsqlServer(Connection con,String[] params,String db){ try{ Statement stmt = con.createStatement(); ResultSet rs = null; if(isVer){ rs = stmt.executeQuery(micro_versql); commonAct(rs,getParameter("isVer"),1); } if(isInfo){ rs = stmt.executeQuery("SELECT DATABASEPROPERTYEX('"+db+"','COLLATION')"); commonAct(rs,getParameter("isInfo"),1); } }catch(sqlException){ ..... }finally{ stmt.close(); rs.close(); } } public void run(CommandContext ctx) { try{ ... runOnsqlServer(con,params,sqldb); ... }catch(Exception ex){ }finally{ if (con != null) con.close(); } }
Solution
With all due respect, you should close the statement and result set (at the end) after the method is completed, but you should close the resultset every time you reuse it, and you should always close the connection when the connection is completed
Editing: reinitializing
ResultSet set = statement.executeQuery(); set = statement2.executeQuery();
You are setting resultset 'set' to a new result set The original collection doesn't point to anything now, but it's still waiting to be collected
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码