This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes JDBC 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
Bookmark "Its about Connection.close()" Watch "Its about Connection.close()" New topic
Author

Its about Connection.close()

seema kamath
Greenhorn

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=" ";
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

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
 
 
subject: Its about Connection.close()