java - What is best way to fetch jdbc connection in sub method -


i have query regarding fetching jdbc connection pool in sub method.following 2 method came across suggest me 1 best avoid connection leakage , tell if other solution.

method 1: getconnection method return connection.

void testmain(){     connection conn = getconnection();     submethod(conn)     conn.close(); } void submethod(connection conn){     // use jdbc connection     return; } 

method2:

void testmain(){     connection conn = getconnection();     submethod()     conn.close(); } void submethod(){     connection conn = getconnection();     conn.close();     return; } 

the place need connection should connection.

the way ensure no resources "leaked" using java 7's try-with-resource syntax:

public string fetchsomedata() {     try (connection conn = getconnection()) { // line, syntax, ensure automatically closed in invisible "finally" block         // need data, return or else     } catch (sqlexception e) {         // no need clean here, log exception or whatever want.     } } 

you can use try-with-resource syntax on objects implement autocloseable interface. includes connection, statement, , resultset among others.

if need transaction might want initialize connection in method, , pass connection different other methods adds transaction, , commit it. if that's case, can do:

public string fetchsomedataintransactionstyle() {     try (connection conn = getconnection()) { // line, syntax, ensure automatically closed in invisible "finally" block         conn.setautocommit(false);         addsomethingtotransaction(conn);         addsomethingmore(conn);         conn.commit();     } catch (sqlexception e) {         // no need clean here, log exception or whatever want.     } } 

Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -