File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes JDBC and Relational Databases and the fly likes Its about Connection.close() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "Its about Connection.close()" Watch "Its about Connection.close()" New topic

Its about Connection.close()

seema kamath

Joined: Nov 27, 2000
Posts: 14
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=" ";
String id=" ";
con=DriverManager.getConnection("jdbc dbc:NWind");
String ls1="DADDY",ls2="polo";
String str= "insert into Customers(customerid,companyName) values (";

int i=st.executeUpdate(str);

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

catch(Exception e)

Please help.Thanks in advance
seema kamath
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
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.

Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
I agree. Here's the link:
subject: Its about Connection.close()
It's not a secret anymore!