Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Its about Connection.close()

 
seema kamath
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello people,
I need some help on this.Im working with MS_Access and the database I'm using is the sample database called NorthWind. I have been successful with select and update statements but then i have problems with insertion.The code below works fine if i remove the comment on con.close().My question is why do i need to explicitly make a call to the connection's close() when i have a garbage collector running for me. I have tried using con= null instead of closing it but the record doesnt get inserted unless i close the connection. I know i can get problems with concurrent executions when i dont close a conncetion but here i'am unable to insert even for the first run of the program.Can,somebody clearly describe as to what is happening when i use a close() there?
I have also taken care of closing the database when executing this program
Here is the code
import java.sql.*;
public class Insert
{
public static void main(String a[])
{Connection con = null,con2=null;
Statement st= null;
ResultSet rs = null;
String cust=" ";
try
{
String id=" ";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc dbc:NWind");
st=con.createStatement();
String ls1="DADDY",ls2="polo";
String str= "insert into Customers(customerid,companyName) values (";
str+="'"+ls1+"','"+ls2+"')";
System.out.println(str);

int i=st.executeUpdate(str);

System.out.println("Insert Success"+i);
// I have commented the following line intentionally
//con.close();

}
catch(Exception e)
{
System.out.println(e);
}
}
}

Please help.Thanks in advance
seema kamath
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the database is some kind of simple sequential file that supports SQL it may be that the insert is in the buffer but isn't flushed to the file until the close statement is reached.
You should always use a close with a connection. It doesn't have anything to do with garbage collection but rather releasing the physical connection to the database itself.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic