• Post Reply Bookmark Topic Watch Topic
  • New Topic

why not set connection=null after close connection  RSS feed

 
chaohua wang
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi folks,

I have seen all examples about database conection like the following.

Connection cn = DriverManager.getConnection("jdbc:hsqldb:file:test5",
"sa", "");
Statement st = cn.createStatement();
ResultSet ts = null;
......
.....
.....
st.close();
ts.close();
cn.close();


after connection is closed , why not set cn = null?
what is disadvantage to set cn=null after cn is closed?

Thank you very much for your help.

Chaohua
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is generally better to let the variable fall out of scope, and the garbage collector will take care of it.
 
chaohua wang
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tnank you,

I wonder if not set connection = null after close, next thread can use this connection again.

I got an exception in my code:
Thread-579 I/O Error: Connection reset
net.sourceforge.jtds.jdbc.TdsCore:TdsCore.java Line: 1049
net.sourceforge.jtds.jdbc.JtdsStatement:JtdsStatement.java Line: 406
net.sourceforge.jtds.jdbc.JtdsStatement:JtdsStatement.java Line: 1258

I guess the reason is that I set connnection=null after close the connection. please help.
 
Jayesh Lalwani
Ranch Hand
Posts: 502
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In most instances, threads should not be sharing connections anyways. From the little information you presented here, it sounds to me like you have multi-threading issues going on.
 
pascal betz
Ranch Hand
Posts: 547
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why do you want to set it to null ? why do you think this could give you more problems ?

setting connection to null will not give you any problems (other than NullPointerException if you try to call a method on the null reference).

A reference is just a "pointer" to an Object. If you set this pointer to null, then this does not affect the Connection other than it might be garbage collected if this was the last pointer to the Object (of course there is more to garbage collection than this...).

if your connection has been resetted/closed then this sounds like a thread/timeout/pool problem.
and by the way:
always use try/catch/finally or try/finally to close connections/statements/resultsets/other resources/streams or to commit/rollback transactions... the code you've showed is not a god example!


cheers

p
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!