Mysterious closing ResultSets

I'm getting desperate for a solution to this problem (as is the rest of the development team!).
Basically we've been trying to create a system that automatically assigns values (frequencies) to objects (nodes) based on a rule set. Each node contains a varying number of sub-objects (radios) and each radio needs one frequency. The database has been set up and has test data for our Solution class to go through. However, we've run into an odd problem where our ResultSets are suddenly closing.
The classes work like this:
Database Broker (handles connection to DB, as well as executeQuery and executeUpdate statements.)
Entry Broker (Holds all SQL statements for data retrieval in various methods. Each method contains an SQL statement to access data, and code to format that data into something useable by the main class.
Solution/Main class (Contains methods to use the data from the Entry Broker to test valid solutions. Certain rules apply to assigning frequencies to radios and this class ensures that the data applies to these rules before it writes the data back to the DB (via the EntryBroker).
The problem we continually run into is that whilst the ResultSets work fine in the Entry Broker, they are closed when they return to the Main class.
Here's the catch: It seems in most cases that only the FIRST ResultSet returned in each method is closed, the remaining ResultSets work fine. We worked around this problem by creating a 'dummy' ResultSet, which obtained data from the database which was never used (the project name). We put this in its own try catch bracket so it would not interrupt the project.
It worked fine for a few classes, but for others (notably the following one) it was ineffective. We've searched and searched but we cannot find anyone with a similar complaint (except a few people who have commented about ODBC version problems). Our ODBC version is 3.520.7713.0
Here's an example method from the Solution class (The entire class is over 1000 lines):
// Method to test Harmonic resonance for nodes within 10m
private boolean resonanceGlobal (boolean tstResonanceG, double txFreq, double rxFreq, int distance)     {
System.out.println("Beginning global harmonic resonance check");
try {
// Getting Nodes
rsNode2 = eBroker.getNodes(projectNo);
// node loop
while (rsNode2.next())     {
System.out.println("602 Test Marker GHarm 1");
// get next node, store in nodeTemp
nodeTemp = rsNode2.getInt(1);
// System out to show which nodes will pass if statement
System.out.println(node + " compare to " + nodeTemp);
// avoid testing the same node against itself
if (nodeTemp != node)     {
// distance check (only neccesary within 10m)
System.out.println("Test Marker Before Distance check");
distance = getDistance(node, nodeTemp, distance);
System.out.println("Test Marker After Distance check");
// distance check if statement
if (distance <= 10)     {
System.out.println("618 Test Marker GHarm 2");
// get the radios of the node, foreign node
rsRadiosTemp = eBroker.getRadios(node);
rsDummy = eBroker.getDummy(projectNo);
rsRadios2 = eBroker.getRadios(nodeTemp);
// This dummy ResultSet normally fails so that
// the other ResultSets perform normally
try {
rsDummy.next();
}     // end try
catch (java.sql.SQLException dummyException)     {
System.out.println("dummyException " + dummyException);
}     // end catch
// radio loop
while (rsRadiosTemp.next())     {     // error occurs here
System.out.println("627 Test Marker GHarm 3");
// loop for foreign node radios
while (rsRadios2.next())     {
System.out.println("631 Test Marker GHarm 4");
// get next radio
radioTemp = rsRadios2.getInt(1);
// get the TX and RX of the radio
genericTX = getTX(radioTemp);
radioTempCon = getConnection(radioTemp);
genericRX = getTX(radioTempCon);
// calculate bounds for harmonics test
txLo = ((txFreq * 2) - genericTX) - 4;     // 4Mhz below TX harmonics check
txHi = ((txFreq * 2) - genericTX) + 4;     // 4Mhz above TX harmonics check
rxHi = ((rxFreq * 2) - genericRX) + 4;     // 4Mhz above RX harmonics check
rxLo = ((rxFreq * 2) - genericRX) - 4;     // 4Mhz below RX harmonics check
// checks TX and RX of foreign radio against TX, RX of current radio for separation
if ((txLo > genericTX && txHi < genericTX) || (rxLo > genericRX && rxHi < genericRX))     {
tstResonanceG = false;     
break;
} //end if
else {
tstResonanceG = true;
}     // end else
} //end foreign radio loop
// breaking out of loops for return
if (tstResonanceG == false)
break;
}     // end radio loop
rsRadios2.close();
rsRadiosTemp.close();
}     // end sameradio check
}     // end distance check
}// end node loop
rsNode2.close();
}     // end try
// Catch statement to stop from crashing in the
// event of an error during SQL statements.
catch (java.sql.SQLException resonanceGlobalException) {
// Prints out the error message produced
System.out.println(resonanceGlobalException);
}     // end catch
// returns result
return tstResonanceG;
} //end checkHarmonicResonanceGlobal()
My apologies if it is a little hard to read, but the indenting is accurate. The Entry Broker methods which this method uses are here:
public ResultSet getNodes (int projectNo) {
// creating SQL statement
sqlStatement = "SELECT nodeNo from tblNode WHERE projectNo = " + projectNo;
System.out.println(sqlStatement);
// executing SQL statement
rsNodes = db.runQuery(sqlStatement);
// returns ResultSet
return rsNodes;
}     // end getNodes
// Method to get the distance between any two nodes
public int getDistance (int projectNo, int node, int tempNode)     {
ResultSet rsX1;                         // Used for obtaining the X-coord of node 1
ResultSet rsX2;                         // Used for obtaining the X-coord of node 2
ResultSet rsY1;                         // Used for obtaining the Y-coord of node 1
ResultSet rsY2;                         // Used for obtaining the Y-coord of node 2
double distance = 0;                    // Used in Global checks
int dist = 0;                              // Used in Global checks
int x1 = 0;                                   // Used in calculating distance
int x2 = 0;                                   // Used in calculating distance
int y1 = 0;                                   // Used in calculating distance
int y2 = 0;                                   // Used in calculating distance
int xDist = 0;                              // Used in calculating distance
int yDist = 0;                              // Used in calculating distance
int distint = 0;                         // Used to store converted values
try {
// get the X and Y co-ordinates of both nodes
sqlStatement = "SELECT xCoord FROM tblNode WHERE nodeNo = " + node + " AND projectNo = " + projectNo;
rsX1 = db.runQuery(sqlStatement);
rsX1.next();
x1 = rsX1.getInt(1);
sqlStatement = "SELECT yCoord FROM tblNode WHERE nodeNo = " + node + " AND projectNo = " + projectNo;
rsY1 = db.runQuery(sqlStatement);
rsY1.next();
y1 = rsY1.getInt(1);
sqlStatement = "SELECT xCoord FROM tblNode WHERE nodeNo = " + tempNode + " AND projectNo = " + projectNo;
rsX2 = db.runQuery(sqlStatement);
rsX2.next();
x2 = rsX2.getInt(1);
sqlStatement = "SELECT yCoord FROM tblNode WHERE nodeNo = " + tempNode + " AND projectNo = " + projectNo;
rsY2 = db.runQuery(sqlStatement);
rsY2.next();
y2 = rsY2.getInt(1);
}     // end try
catch (java.sql.SQLException getDistanceException) {
System.out.println(getDistanceException);
// calculating distance
yDist = y2 - y1;
xDist = x2 - x1;
// perform pythagoras theorem for distance
dist = (xDist * xDist) + (yDist * yDist);
distance = java.lang.Math.sqrt(dist);
Double roundFreqTemp = new Double(freqTemp);
distint = roundFreqTemp.intValue() ;
return distint;
} // end get distance method
// Method to get all the radios in a node
public ResultSet getRadios(int node)     {
ResultSet rsRadios;          // Used for obtaining radios in a node
// creating sql Statement
sqlStatement = "SELECT * FROM tblRadio WHERE nodeNo =" + node;
System.out.println(sqlStatement);
// executing sql Statement
rsRadios = db.runQuery(sqlStatement);
System.out.println("EB Test Marker 1: Line 261");
// returning radio no
return rsRadios;
}//end getRadio
public double getTX(int radioTemp){
double txTemp = 0;     // Used for storing TX of a radio
int freqNoTemp = 0; // Used for storing the frequency ID
rsDummy = getDummy(projectNo);
// creating SQL statement
sqlStatement ="Select frequencyNo from tblRadio where radioNo = " + radioTemp;
System.out.println(sqlStatement);
// executing SQL statement
rsTX = db.runQuery(sqlStatement);
try {
System.out.println("Test Marker EB1: 317");
try {
rsDummy.next();
}     // end try
catch     (java.sql.SQLException dummyException)     {
System.out.println("dummyException" + dummyException);
}     // end catch
System.out.println("Test MarkerEB2: 330");
// moving to first position in rs
rsTX.next();
System.out.println("Test MarkerEB3: 334");
// obtaining data from rs
freqNoTemp = rsTX.getInt(1);
System.out.println("Test MarkerEB4: 337");
rsTX.close();
}     // end try
catch (java.sql.SQLException rsTXException)     {
System.out.println("rsTXExeption: " + rsTXException);
}     // emd catch
System.out.println("Frequency No is: " + freqNoTemp);
rsDummy = getDummy(projectNo);
sqlStatement = "Select frequency from tblFreq where frequencyNo = " + freqNoTemp;
System.out.println(sqlStatement);
rsRX = db.runQuery(sqlStatement);
try {
try {
System.out.println("Test MarkerEB6: 361");
rsDummy.next();
}     // end try
catch     (java.sql.SQLException dummyException)     {
System.out.println("dummyException" + dummyException);
}     // end catch
System.out.println("Test MarkerEB5: 373");
rsRX.next();
System.out.println("Test MarkerEB7: 376");
txTemp = rsRX.getDouble(1);
System.out.println("Test MarkerEB8: 379");
rsRX.close();
}     // end try
catch (java.sql.SQLException rxException) {
System.out.println("rxException " + rxException);
} // end catch
     System.out.println("393 Before return");
return txTemp;
}     //end getTX
public int getConnection(int radio) {
int nodeCon = 0;                    // Used to return the connected node no
ResultSet rsConnection;          // Used for obtaining the foreign radio
// creating SQL statement
sqlStatement = "SELECT radioNo FROM tblRadio where recRadio = " + radio;
System.out.println(sqlStatement);
// executing SQL statement
rsConnection = db.runQuery(sqlStatement);
try {
// moving to first position in rs
rsConnection.next();
// obtaining data from rs
nodeCon = rsConnection.getInt(1);
}     // end try
catch (java.sql.SQLException getConnectionException) {
System.out.println("getConnectionException : " + getConnectionException);
}     // end catch
// returns node no.
return nodeCon;
And finally, the dummy rs:
// Dummy method to fix resultSet closed error
public ResultSet getDummy (int projectNo) {
sqlStatement = "Select projectName from tblProject where projectNo = " + projectNo;
System.out.println(sqlStatement);
rsDummy = db.runQuery(sqlStatement);
return rsDummy;
Here is some sample output that we have:
----jGRASP exec: java MainGui
slider value constructor: 50
116: if(singleton==null) {
120: singleton=new Resolvotron
Connection to D/Base establised
Select projectName from tblProject where projectNo = 3
Init OK. Beginning solve process
main OK: beginning frequency assign process
SELECT nodeNo from tblNode WHERE projectNo = 3
267: Node number = 2
SELECT * FROM tblRadio WHERE nodeNo =2
EB Test Marker 1: Line 261
Test Marker 1: Line 289
298: Radio number = 4
Test Marker 5: Line 308
Test Marker 3: Line 313
SELECT frequency from tblFreq WHERE projectNo = 3
125.5
Beginning test process
Test Marker 4: Line 386
Beginning check 257072
Test Marker 6: Line 774
70 Mhz Margin = false
Beginning local 10Mhz separation check
SELECT * FROM tblRadio WHERE nodeNo =2
EB Test Marker 1: Line 261
Getting TX of radio: 4
Select projectName from tblProject where projectNo = 3
Select frequencyNo from tblRadio where radioNo = 4
Test Marker EB1: 317
dummyExceptionjava.sql.SQLException: ResultSet is closed
Test MarkerEB2: 330
Test MarkerEB3: 334
Test MarkerEB4: 337
Frequency No is: 2
Select projectName from tblProject where projectNo = 3
Select frequency from tblFreq where frequencyNo = 2
Test MarkerEB6: 361
dummyExceptionjava.sql.SQLException: ResultSet is closed
Test MarkerEB5: 373
Test MarkerEB7: 376
Test MarkerEB8: 379
393 Before return
432: getting connection
SELECT radioNo FROM tblRadio where recRadio = 4
438: getting TX of radio: 6
Select projectName from tblProject where projectNo = 3
Select frequencyNo from tblRadio where radioNo = 6
Test Marker EB1: 317
dummyExceptionjava.sql.SQLException: ResultSet is closed
Test MarkerEB2: 330
Test MarkerEB3: 334
Test MarkerEB4: 337
Frequency No is: 2
Select projectName from tblProject where projectNo = 3
Select frequency from tblFreq where frequencyNo = 2
Test MarkerEB6: 361
dummyExceptionjava.sql.SQLException: ResultSet is closed
Test MarkerEB5: 373
Test MarkerEB7: 376
Test MarkerEB8: 379
393 Before return
java.sql.SQLException: ResultSet is closed
10 Mhz Local = true
Beginning 10 Mhz separation check
SELECT nodeNo from tblNode WHERE projectNo = 3
Node number is 2
10 Mhz Global = false
Beginning local harmonic resonance check
SELECT * FROM tblRadio WHERE nodeNo =2
EB Test Marker 1: Line 261
Select projectName from tblProject where projectNo = 3
Select frequencyNo from tblRadio where radioNo = 4
Test Marker EB1: 317
dummyExceptionjava.sql.SQLException: ResultSet is closed
Test MarkerEB2: 330
Test MarkerEB3: 334
Test MarkerEB4: 337
Frequency No is: 2
Select projectName from tblProject where projectNo = 3
Select frequency from tblFreq where frequencyNo = 2
Test MarkerEB6: 361
dummyExceptionjava.sql.SQLException: ResultSet is closed
Test MarkerEB5: 373
Test MarkerEB7: 376
Test MarkerEB8: 379
393 Before return
SELECT radioNo FROM tblRadio where recRadio = 4
Select projectName from tblProject where projectNo = 3
Select frequencyNo from tblRadio where radioNo = 6
Test Marker EB1: 317
dummyExceptionjava.sql.SQLException: ResultSet is closed
Test MarkerEB2: 330
Test MarkerEB3: 334
Test MarkerEB4: 337
Frequency No is: 2
Select projectName from tblProject where projectNo = 3
Select frequency from tblFreq where frequencyNo = 2
Test MarkerEB6: 361
I'll leave it at that, since the program goes into an endless loop. The dummy Exceptions are our dummy resultsets crashing so the rest can survive. The other stuff is from different methods. You should be able to locate the logic of the program by following the System.outs
Test Markers with EB refer to the Entry Broker.
Any help would be appreciated since we cannot find any other way of running this class successfully.
Steve

Ok problem solved...
Basically I was calling one ResultSet after another. Thanks to the Database Broker's structure, this was killing the first ResultSet. I fixed up the loops so that ResultSets were only ever called just before they were needed, and it fixed the problem. The only other errors were simple logic faults which I drummed out in short order. Thanks for the help everyone!

Similar Messages

  • Please Help !  Exception in closing resultset,statement.

    In an application developed on , i am closing the resultsets and statements in finally block as
    finally {
         if (resultset != null) resultset .close();
         if (statement != null) statement.close();
    the above block does not take care of exceptions that might arise while closing resultset/statement. Please help with this:
    what the conditions exceptions may arise in closing resultset/statements.
    when does the garbage collector free such resources and what are the implications of not catching exception while closing - can this cause database handle leaks.
    Please help!

    I don't know what exceptions might occur, but since the close() method can throw SQLException, your program has to catch it. Maybe if you close twice, the second time will throw an exception? Anyway, it doesn't really matter, you still have to write a try-catch around it. What you do there is up to you -- you could ignore it (which is what I do) or you could end the program with a message.
    When does the garbage collector free those resources? The garbage collector only frees memory. Nothing else. And the garbage collector will free a ResultSet object only when there are no references to it anywhere in your program. That doesn't mean just in code that you wrote, but anywhere in code that's running in your program. For example, the Statement object that produced the ResultSet might hold a reference to it. However, the API documentation for ResultSet does say that when the garbage collector does free a ResultSet object, it will automatically close it.
    However, the best practice is to close ResultSet and Statement objects when you are finished with them, and not rely on garbage collection to clean up after you.

  • Too many connections - even after closing ResultSets and PreparedStatements

    I'm getting a "Too many connections" error with MySQL when I run my Java program.
    2007-08-06 15:07:26,650 main/CLIRuntime [FATAL]: Too many connections
    com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException: Too many connections
            at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:921)
            at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2870)
            at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:812)
            at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3269)
            at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1182)
            at com.mysql.jdbc.Connection.createNewIO(Connection.java:2670)I researched on this and found out that I wasn't closing the ResultSet and the PreparedStatement.
    The JDBC connection is closed by a central program that handles connections (custom connection pooling).
    I added the code to close all ResultSets and PreparedStatements, and re-started MySQL as per the instructions here
    but still get "Too many connections" error.
    A few other things come to mind, as to what I may be doing wrong, so I have a few questions:
    1) A few PreparedStatements are created in one method, and they are used in a 2nd method and closed in the 2nd method
    does this cause "Too many connections" error?
    2) I have 2 different ResultSets, in nested while loops where the outer loop iterates over the first ResultSet and
    the inner loop iterates over the second ResultSet.
    I have a try-finally block that wraps the inner while loop, and I'm closing the second ResultSet and PreparedStement
    in the inner while loop.
    I also have a try-finally block that wraps the outer while loop, and I'm closing the first ResulSet and PreparedStatement
    in the outer while loop as soon as the inner while loop completes.
    So, in the above case the outer while loop's ResultSet and PreparedStatements remain open until the inner while loop completes.
    Does the above cause "Too many connections" error?
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    The following is relevant sections of my code ( it is partially pseudo-code ) that shows the above 2 cases:
    init( Connection jdbcConnection ){
       String firstSQLStatement = "....";
       PreparedStatement ps1 = jdbcConnection.prepareStatement( firstSQLStatement );
       String secondSQLStatement = "....";
       PreparedStatement ps2 = jdbcConnection.prepareStatement( secondSQLStatement );
       String thirdSQLStatement = "....";
       PreparedStatement ps3 = null;
       ResultSet rsA = null;
       try{
            ps3 = jdbcConnection.prepareStatement( thirdSQLStatement );
            rsA = ps3.executeQuery();
            if( rsA.next() ){
                   rsA.getString( 1 );
       }finally{
            if( rsA != null )
                   rsA.close();
            if( ps3 != null )
              ps3.close();
       //Notice, how ps1 and ps2 are created here but not used immediately, but only ps3 is
       //used immediately.
       //ps1 and ps2 are used in another method.
    run( Connection jdbcConnection ){
         ResultSet rs1 = ps1.executeQuery();
            try{
               while(rs1.next()){
                    String s = rs1.getString();
                    ps2.setString(1, s);
              ResultSet rs2 = ps2.executeQuery();
                    try{
                   while(rs2.next()){
                        String s2 = rs2.getString();
                    }finally{
                   if( rs2 != null )
                     rs2.close();
                   if( ps2 != null )
                     ps2.close();
         }catch( Exception e ){
              e.printStackTrace();
         }finally{
            if( rs1 != null )
                  rs1.close();
               if( ps1 != null )
                  ps1.close();
    //Notice in the above case rs1 and ps1 are closed only after the inner
    //while loop completes.
    }I appreciate any help.

    Thanks for your reply.
    I will look at the central connection pooling mechanism ( which was written by someone else) , but that is being used by many other Java programs others have written.
    They are not getting this error.
    An addendum to my previous note, I followed the instructions here.
    http://dev.mysql.com/doc/refman/5.0/en/too-many-connections.html
    There's probably something else in my code that is not closing the connection.
    But I just wanted to rule out the fact that opening a PreparedStatement in one method and closing it in another is not a problem.
    Or, if nested ResultSet loops don't cause the problem.
    I've read in a few threads taht "Too many connections" can occur for unclosed RS and PS , and not just JDBC connections.

  • Unclear about closing ResultSets

    Please provide clarification: The JavaDoc for ResultSets says that you don't have to explicitly close ResultSet objects since the RS will be closed when its defining Statement is closed or when the RS is garbage collected.
    The Oracle JDBC Developer's Guide and Reference states (in the section titled "Closing the Result Set and Statement Objects"):
    "You must explicitly close the ResultSet and Statement objects after you finish using them. This applies to all
    ResultSet and Statement objects you create when using the Oracle JDBC drivers. The drivers do not have
    finalizer methods; cleanup routines are performed by the close() method of the ResultSet and Statement
    classes. If you do not explicitly close your ResultSet and Statement objects, serious memory leaks could
    occur. You could also run out of cursors in the database."
    So, does the Oracle driver operate differently than the JDBC standard in this regard?

    The JavaDoc for ResultSets says that you don't have to explicitly close ResultSet objects since the RS will be closed when its defining Statement is closed or when the RS is garbage collected.In Oracle JDBC, if you close the statement, then the result set is also closed, unless you obtained the result set as an OUT parameter from a stored procedure or function that returns a REF CURSOR.
    However, it is definitely not prudent to wait until the result set is garbage collected, since you have no explicit control over that! Depending on your database setup, you'll typically be able to open a couple dozen statements before you start running out of database cursors.
    This is even more important if you are using SQLJ: there statements are automatically managed for you, so you'll never have to worry about closing them. However, if you do not close result sets (called iterators in SQLJ), the associated statement will be kept around and stays open (again, it might be garbage collected or it might not - no guarantees).

  • Closing resultsets in loop

    I have code that creates dynamic SQL statements in a loop to search for a value in a table. The Where clause is changed in each iteration of the loop until the value is found or the loop finishes. The code looks something like this:
    (Sorry for the crappy formatting of the code. I tried indenting lines, but when I previewed it, it aligned everything. Damn )
    /* NOTE: variables were changed to fit in this page better */
    for( int i = 9; i >=0;i--) {
    SelectSQL = new StringBuffer("SELECT col FROM tab WHERE ");
    for( int j = 0; j <= i;j++) {
    SelectSQL.append( "col" + j + "ID = " + Val[j]);
    if( j != i ) { SelectSQL.append(","); }
    stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY,
    ResultSet.CONCUR_READ_ONLY );
    rs = stmt.executeQuery(SelectSQL.toString());
    if( rs.next() ) {
    ValID = rs.getLong(1);
    /* TODO: Should I be closing these in loops? */
    rs.close();
    stmt.close();
    if( ValID > 0 ) { break; }
    My question is: Do I need to close the resultset(rs) and statement(stmt) at the bottom of the loop? That does not seem very efficient to me, but I am not sure. Any advice would be greatly appriciated. Thanks for your time.

    declare the statement out of the loop and close it on the
    end (also out of the loop) so you reuse the statement each time,
    if the ResultSet is empty it closes, also if you loop through it it closes itself, when it is empty, but i recommend to close it each time you use it anyway (in the loop)
    don't forget, only select statements return a resultset .. others (delete, update) don't

  • Getting java.lang.NullpointerException while closing resultset aft using it

    Hi,
    I kindly request to share your ideas reg. my problem.
    I am opening a database connection using connection pool and i am using two or more resultsets and statement objects.I am closing these objects at the end of their usage.But i am getting java.lang.NullpointerException when i close them(if i don't close them it works fine). what might be the reason. Had i did any thing wrong in the code.
    please view the code
    public String storeNewConnection(String CIRCLE,String DIVISION,String SUB_DIVISION,String SECTION,String CONSUMER_NAME,String FATHER_NAME,String STREET_NAME,String DOOR_NO,String TOWN_CITY,String LAND_MARK,String PINCODE,String STDCODE,String PHONE_NO,String EMAIL,String NEIGHBOUR_SCNO,String DOCUMENT_CODE,String LT_APR_NO,String year1,String month1,String day1,String PCBNO,String CONSUMER_STATUS,String SOCIAL_GROUP,String CATEGORY_SUPPLY,String LOCATION_PREMISES,String PURPOSE_OF_SUPPLY,String DURATION,String LOAD_TYPE,String CONNECTED_LOAD,String CONTRACTED_LOAD,String APPLICATION_FEE,String DEVELOPMENT_CHARGES,String SECURITY_DEPOSIT,String ADDL_SECURITY_DESPOSIT,String DEPOSITED_THRU,String DD_CHEQUE_DETAILS,String year2,String month2,String day2,String REMARKS,String POLE_NO)
              int count=0;
              Statement st=null;
              ResultSet rs=null,rs1=null,rs2=null,rs3=null;
              PreparedStatement pst=null;
              String result="",query="",sysDate="",sysDate2="";
              String reg_no = "";
              try
                   st=con.createStatement();
                   //Check dates with sys date
                   String date1 =null;                    
                   String date2 =null;
                   if(! (year1.equals("") || month1.equals("") || day1.equals("")) )
                        date1=day1+"-"+month1+"-"+year1;
                        rs2=st.executeQuery("select round(to_date('"+date1+"','dd-Mon-yyyy')-to_date(sysdate,'dd-Mon-yy')) from dual");
                        rs2.next();
                        if(rs2.getInt(1) != 0)
                             return "false";                              
                   if(! (year2.equals("") || month2.equals("") || day2.equals("")) )
                        date2=day2+"-"+month2+"-"+year2;
                        rs3=st.executeQuery("select round(to_date('"+date2+"','dd-Mon-yyyy')-to_date(sysdate,'dd-Mon-yy')) from dual");
                        rs3.next();
                        if(rs3.getInt(1) != 0)
                             return "false";     
                   rs1=st.executeQuery("select to_char(sysdate,'yyyyMONdd'),to_char(sysdate,'dd-Mon-yyyy') from dual");
                   rs1.next();
                   sysDate=rs1.getString(1);
                   sysDate2=rs1.getString(2);
                   rs=st.executeQuery("select max(SERIAL_NO) from NEW_CONNECTIONS where to_char(sysdate,'yyyy') = to_char(REG_DATE,'yyyy') and to_char(sysdate,'mm') = to_char(REG_DATE,'mm') and SUB_DIVISION_CODE = "+SUB_DIVISION+" and DIVISION_CODE = "+DIVISION+" and CIRCLE_CODE = "+CIRCLE+" ");
                   if(rs.next())
                        count = rs.getInt(1);
                        count++;                              
                   else
                        count=1;
                   query="insert into NEW_CONNECTIONS ( "+
                        " REG_NO,SERIAL_NO,REG_DATE,CIRCLE_CODE,DIVISION_CODE,SUB_DIVISION_CODE,SECTION_CODE, "+
                        " CONSUMER_NAME,FATHER_NAME,STREET_NAME,DOOR_NO,TOWN_CITY,LAND_MARK,PINCODE, "+
                        " STDCODE,PHONE_NO,EMAIL,NEIGHBOUR_SCNO,DOCUMENT_CODE,LT_APR_NO,LT_APR_DATE, "+
                        " PCBNO,CONSUMER_STATUS,SOCIAL_GROUP,CATEGORY_SUPPLY,LOCATION_PREMISES,PURPOSE_OF_SUPPLY,"+
                        " DURATION,LOAD_TYPE,CONNECTED_LOAD,CONTRACTED_LOAD,APPLICATION_FEE,DEVELOPMENT_CHARGES, "+
                        " SECURITY_DEPOSIT,ADDL_SECURITY_DEPOSIT,DEPOSITED_THRU,DD_CHEQUE_DETAILS,DD_CHEQUE_DATE,REMARKS,APPLICATION_STATUS,POLE_NO) "+
                        " values(?,?,'"+sysDate2+"',?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                   pst = con.prepareStatement(query);
                   String cnt ="";
                   if(count <= 9)
                        cnt="0000";
                   else if(count <= 99)
                        cnt="000";
                   else if(count <= 999)
                        cnt="00";
                   else if(count <= 9999)
                        cnt="0";
                   cnt+=Integer.toString(count);
                   reg_no = CIRCLE+DIVISION+SUB_DIVISION+SECTION+"N"+cnt+sysDate;               
                   int serial_no =count;
                   int pin = 0;
                   if(!PINCODE.equals(""))
                        pin =Integer.parseInt(PINCODE);
                   int std = 0;
                   if(!STDCODE.equals(""))
                        std = Integer.parseInt(STDCODE);
                   int status = Integer.parseInt(CONSUMER_STATUS);
                   int social_group = Integer.parseInt(SOCIAL_GROUP);
                   int supply = Integer.parseInt(CATEGORY_SUPPLY);
                   int location = Integer.parseInt(LOCATION_PREMISES);
                   int purpose = Integer.parseInt(PURPOSE_OF_SUPPLY);
                   int duration = Integer.parseInt(DURATION);
                   int laod_type = Integer.parseInt(LOAD_TYPE);
                   float conn_load = Float.parseFloat(CONNECTED_LOAD);
                   int cont_load = 0;
                   if(!CONTRACTED_LOAD.equals(""))
                        cont_load =Integer.parseInt(CONTRACTED_LOAD);
                   int app_fee = Integer.parseInt(APPLICATION_FEE);
                   int dev_chg = Integer.parseInt(DEVELOPMENT_CHARGES);
                   int sec_dep = Integer.parseInt(SECURITY_DEPOSIT);
                   int addl_sec_dep = 0;     
                   if(!ADDL_SECURITY_DESPOSIT.equals(""))
                        addl_sec_dep =Integer.parseInt(ADDL_SECURITY_DESPOSIT);
                   int dep_thru = Integer.parseInt(DEPOSITED_THRU);          
                   pst.setString(1,reg_no);
                   pst.setInt(2,serial_no);
                   pst.setString(3,CIRCLE);
                   pst.setString(4,DIVISION);
                   pst.setString(5,SUB_DIVISION);
                   pst.setString(6,SECTION);
                   pst.setString(7,CONSUMER_NAME);
                   pst.setString(8,FATHER_NAME);
                   pst.setString(9,STREET_NAME);
                   pst.setString(10,DOOR_NO);
                   pst.setString(11,TOWN_CITY);
                   pst.setString(12,LAND_MARK);
                   pst.setInt(13,pin);
                   pst.setInt(14,std);
                   pst.setString(15,PHONE_NO);
                   pst.setString(16,EMAIL);
                   pst.setString(17,NEIGHBOUR_SCNO);
                   pst.setString(18,DOCUMENT_CODE);
                   pst.setString(19,LT_APR_NO);
                   pst.setString(20,date1);
                   pst.setString(21,PCBNO);
                   pst.setInt(22,status);
                   pst.setInt(23,social_group);
                   pst.setInt(24,supply );
                   pst.setInt(25,location);
                   pst.setInt(26,purpose);
                   pst.setInt(27,duration);
                   pst.setInt(28,laod_type);
                   pst.setFloat(29,conn_load );
                   pst.setInt(30,cont_load);
                   pst.setInt(31,app_fee);
                   pst.setInt(32,dev_chg);
                   pst.setInt(33,sec_dep);
                   pst.setInt(34,addl_sec_dep);
                   pst.setInt(35,dep_thru );
                   pst.setString(36,DD_CHEQUE_DETAILS);
                   pst.setString(37,date2);
                   pst.setString(38,REMARKS);
                   pst.setInt(39,1);
                   pst.setString(40,POLE_NO);
                   pst.executeUpdate();
                   result=reg_no;                                   
                   rs.close();
                   rs=null;
                   rs1.close();
                   rs1=null;
                   rs2.close();
                   rs2=null;
                   rs3.close();
                   rs3=null;
                   st.close();
                   st=null;
                   pst.close();
                   pst=null;
              catch(Exception e)
                   e.printStackTrace();
                   result="false";
                   return result;
              finally
                   if (rs != null)
                        try
                             rs.close();
                        catch (SQLException e)
                        rs = null;
                   if (rs1 != null)
                        try
                             rs1.close();
                        catch (SQLException e)
                        rs1 = null;
                   if (rs2 != null)
                        try
                             rs2.close();
                        catch (SQLException e)
                        rs2 = null;
                   if (rs3 != null)
                        try
                             rs3.close();
                        catch (SQLException e)
                        rs3 = null;
                   if (st != null)
                        try
                             st.close();
                        catch (SQLException e)
                        st = null;
                   if (pst != null)
                        try
                             pst.close();
                        catch (SQLException e)
                        pst = null;
              return result;
    Also plz help me to improve the code if necessary so that it will work fine for multiple users
    thaks & regards
    Prasanth.C

    Thanks a lot.
    i replaced the code below
    if (rs != null)
                        try
                             rs.close();
                        catch (SQLException e)
                        rs = null;
                   if (rs1 != null)
                        try
                             rs1.close();
                        catch (SQLException e)
                        rs1 = null;
                   if (rs2 != null)
                        try
                             rs2.close();
                        catch (SQLException e)
                        rs2 = null;
                   if (rs3 != null)
                        try
                             rs3.close();
                        catch (SQLException e)
                        rs3 = null;
                   if (st != null)
                        try
                             st.close();
                        catch (SQLException e)
                        st = null;
                   if (pst != null)
                        try
                             pst.close();
                        catch (SQLException e)
                        pst = null;
    instead of blindly closing the resultsets and statements
    now it works fine.
    One more thing, is my code structurally correct, i mean the variables, try...catch blocks,results,statements,database connections and overall coding. whether it looks like professional code.
    thaks & regards,
    Prasanth.C

  • Closing resultset and statements

    Hi!
    I just got told that I do not need to close my resultsets and statements in the code, it it enough that the connection are closed. Is this correct?
    Eg:
    public method myMethod() {
    ResultSet rs = null;
    Statement sqlStmt = null;
    try {
    query = "SELECT something";
    rs = sqlStmt.executeQuery(query);
    if (rs.next())
    do something...
    // close rs
    if (rs != null) {
    rs.close();
    rs = null;
    sqlStmt.close();
    sqlStmt = null;
    } // end try
    catch (errors)...
    finally {
    if (con != null) {                   <-- Is this line enough to close everything and release connections?
    try {
    con.close();
    catch (exception)...
    } // end finally

    No, you have to explicitly close the resultset, statement, and connection in order to release resources allocated to each of them. Closing the connection will only relase the connection, not the resultset, and statement.
    you could do all of it in the finally as follows:
    finally {
         try {
              if (rs != null) {
                   rs.close();
              if (stmt != null) {
                   stmt.close();
              if (conn != null) {
                   conn.close();
         } catch (Exception e) {}
    also there is no need to set rs = null, stmt = null after the close()

  • Not closing ResultSet, but not getting ORA-01000

    I have an application that is generating the familiar ORA-01000 error.
    Whilst investigating the problem, I wrote a small test program. In the test program I tried to get the ORA-01000, but I don't get it (has anyone ever complained about not getting ORA-01000 before?!)
    connection = DriverManager.getConnection("<connection string>");
    String sql = "SELECT c1 FROM pdtab2 WHERE Id>=? AND Id<=?";
    PreparedStatement ps = connection.prepareStatement(sql);
    for (int i = 1; i <= 30000; ++i)
        ps.setInt(1, i-1);
        ps.setInt(2, i+1);
        if (i % 100 == 0)
            System.out.println("i=" +i);
            System.out.println("getCurrentOpenCursors(connection)="
                               +getCurrentOpenCursors(connection));
        try
            rs = ps.executeQuery();
            while (rs.next())
                result = rs.getInt(1);
        catch (SQLException e2)
            e2.printStackTrace();
        finally
            // Do nothing! Do not close the result set
    }getCurrentOpenCursors does:
    select count(*) AS COUNT from v$open_cursor where user_name like 'me'
    I have reduced OPEN_CURSORS down from 300 to 100, but getCurrentOpenCursors always returns less that what it is set to. Suggesting that OPEN_CUSRORS is not a limit, but rather a pool size?
    The result set returns more than one record, I never close the result set, yet I do not get an ORA-01000 error. I have tried auto-commit true and false on the connection. Is the prepared statement closing its previous result set on each new iteration of the loop, hence stopping me getting a problem?
    I am using Oracle version 10.2.0.1, the corresponding ojdbc14.jar, and Java 1.4.
    Thanks,
    Paul

    Here is a program that does that for you.
    To fix the program, un-comment the line 24 of the code and run again.
    C:\> type TestCursors.java
    import java.lang.* ;
    import java.util.* ;
    import java.sql.* ;
    import oracle.jdbc.* ;
    public class TestCursors
        public static void main(String[] args) throws SQLException, ClassNotFoundException
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection connection = DriverManager.getConnection("jdbc:oracle:oci:@localhost:1521:ORCL");
            ResultSet rs ;
            PreparedStatement ps ;
            for (int i = 1; i <= 30000; ++i)
                String sql = "SELECT 20 FROM scott.emp WHERE deptno = ?";
                ps = connection.prepareStatement(sql);
                ps.setInt(1, 10);
                try
                    rs = ps.executeQuery();
                    rs.close() ;
                    //ps.close() ;
                catch (SQLException e2)
                    System.out.println("The value if i is " + i) ;
                    throw e2 ;
    C:\> javac TestCursors.java
    C:\> java TestCursors
    The value if i is 301
    Exception in thread "main" java.sql.SQLException: ORA-01000: maximum open cursors exceeded
            at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:111)
            at oracle.jdbc.driver.T2CConnection.checkError(T2CConnection.java:671)
            at oracle.jdbc.driver.T2CConnection.checkError(T2CConnection.java:597)
            at oracle.jdbc.driver.T2CPreparedStatement.executeForDescribe(T2CPreparedStatement.java:570)
            at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1030)
            at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1123)
            at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3284)
            at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3328)
            at TestCursors.main(TestCursors.java:22)
    C:\>

  • How could I Fix this problem .. ResultSet closed

    In my JSP page after 4or 5 refreshings i am getting an exeption either saying "Invalid state for getResultSet" of "ResultSet is closed". I'm not getting this if i refresh again. I've tried even by closing ResultSet, Statement and Connection objects at the end of page. Can u give me the solution

    This is correct, unless the guy is lucky enough to be using a driver that adheres to JDBC 3. Try unloading the ResultSet object into a cache and then referencing that on subsequent calls to the page, (unless data staleness is an issue). You'd probably find it useful to browse some of the data transfer patterns to understand the deeper issues in what you're doing.

  • PreparedStatement ResultSet wrapper to auto close cursor

    Hi !
    Is it possible to create wrapper that will automatically close result set and prepared statements ?
    I am sick of closing resultsets and preparedstatements in all my dao objects. Its all about neverending try catch and close code lines, it is all against the java garbage collector idea.
    Do you have any workaround ? Or I need to use with those try catch and close.
    Thanks !

    when u allocate object u dont need to call free nor destory when u dont need the object anymore.
    on the other hand, you need to call .close() when u dont need the prepared statement anymore

  • Implicit vs explicit close of resultsets and statements?

    Hi friends.I am a newbie Java Developer..Okay Here goes
    I have just made a LAN based Java application using Swing,JDBC with backend as MS-Access..The backend is on a shared network drive..
    The application is distributed as jar files on the LAN PCs..
    Everywhere I have connected to the database I have just closed the connection explicitly like this
    con.close();
    I do not close the associated resultset and statement explicitly
    The specification says associated statements and resultsets close when you close
    the connection,even if you don't explicitly close them
    Also I am not using connection pool..its simple basic connection using DriverManager
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String url = "jdbcdbcSN name";
    String user = "";
    String pw = "";
    con = DriverManager.getConnection(url, user, pw);
    Statement stmt = con.createStatement();
    String select = "" ;
    ResultSet rows = stmt.executeQuery(select);
    On the net everyone says to explicitly close everything..but I did not know that
    earlier..
    If specification says everything closes on
    closing connection why do ppl insist on closing everything explicitly..?
    Or is this driver dependent..don't the drivers go through the specification..
    My driver is the Sun JDBC ODBC bridge.....
    I found this method DriverManager.setLogwriter()
    It prints out a trace of all JDBC operations..
    So I ran a sample program with this method included...
    I redirected output to a log file..
    In that program I just explicitly close the connection without closing the
    statements and resultsets explicitly...
    After running the program and seeing the log I saw that the statements
    and resultsets are closed implicitly If I just close the connection explicitly..
    I am putting the log file and the code..
    Have a look at the end of the log file..
    Code
    import java.sql.;
    import java.io.;
    class gc4test
    public static void main(String args[])
    Connection con = null;
    try
    FileWriter fwTrace = new FileWriter("c:\\log.txt");
    PrintWriter pwTrace= new PrintWriter(fwTrace);
    DriverManager.setLogWriter(pwTrace);
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String url = "jdbc:odbc:pravahcon";
    String user = "admin";
    String pw = "ash123";
    con = DriverManager.getConnection(url, user, pw);
    Statement stmt = con.createStatement();
    Statement stmt1 = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
    Statement stmt2 = con.createStatement();
    Statement stmt3 = con.createStatement();
    Statement stmt4 = con.createStatement();
    Statement stmt5 = con.createStatement();
    Statement stmt6 = con.createStatement();
    Statement stmt7 = con.createStatement();
    String select = "SELECT * FROM Users" ;
    ResultSet rows = stmt.executeQuery(select);
    ResultSet rows1 = stmt1.executeQuery(select);
    while(rows.next())
    con.close();
    catch (ClassNotFoundException f)
    System.out.println(f.getMessage());
    System.exit(0);
    catch (SQLException g)
    System.out.println(g.getMessage());
    System.exit(0);
    catch (Exception e)
    System.out.println(e.getMessage());
    System.exit(0);
    End of Log File
    Setting statement option (SQLSetStmtAttr), hStmt=50275112, fOption=25
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    End of result set (SQL_NO_DATA)
    *Connection.close
    8 Statement(s) to close
    *Statement.close
    Free statement (SQLFreeStmt), hStmt=50281544, fOption=1
    deregistering Statement sun.jdbc.odbc.JdbcOdbcStatement@2e7263
    *Statement.close
    Free statement (SQLFreeStmt), hStmt=50277224, fOption=1
    deregistering Statement sun.jdbc.odbc.JdbcOdbcStatement@1bf216a
    *Statement.close
    *ResultSet.close
    *ResultSet has been closed
    Free statement (SQLFreeStmt), hStmt=50274224, fOption=1
    deregistering Statement sun.jdbc.odbc.JdbcOdbcStatement@156ee8e
    *Statement.close
    Free statement (SQLFreeStmt), hStmt=50280464, fOption=1
    deregistering Statement sun.jdbc.odbc.JdbcOdbcStatement@c20e24
    *Statement.close
    Free statement (SQLFreeStmt), hStmt=50278304, fOption=1
    deregistering Statement sun.jdbc.odbc.JdbcOdbcStatement@12ac982
    *Statement.close
    *ResultSet.close
    *ResultSet has been closed
    Free statement (SQLFreeStmt), hStmt=50275112, fOption=1
    deregistering Statement sun.jdbc.odbc.JdbcOdbcStatement@e0e1c6
    *Statement.close
    Free statement (SQLFreeStmt), hStmt=50276144, fOption=1
    deregistering Statement sun.jdbc.odbc.JdbcOdbcStatement@6ca1c
    *Statement.close
    Free statement (SQLFreeStmt), hStmt=50279384, fOption=1
    deregistering Statement sun.jdbc.odbc.JdbcOdbcStatement@1389e4
    Disconnecting (SQLDisconnect), hDbc=50271048
    Closing connection (SQLFreeConnect), hDbc=50271048
    Closing environment (SQLFreeEnv), hEnv=50270880
    So like what these implicitly closed statements and resultsets are different from explicitly closed
    resultsets and statements..?

    Please do not crosspost/doublepost the same question again. It is rude in terms of netiquette.
    Stick to one topic: [http://forums.sun.com/thread.jspa?threadID=5393387&messageID=10745794#10745794].

  • Java Database Connections couldn't be closed on PI 7.1 EHP1

    Hi,  I develop a dynamic web project to PI. And I use Database conection in that web project. Even  I closed the connection in java , Connection doesn't closed and after a while PI pooling size reach the maximum size and PI doesn't response.  I find open connections on MSSQL and connections' status are sleeping, cmd fields are AWAITING COMMAND.  I have to restart  PI these to close that connections.
    I get Connections like these code
                            InitialContext cxt = new InitialContext();
                   final DataSourceManager dsm = (DataSourceManager) cxt
                             .lookup("dbpool");
                            String lookUpName = dsm.getSystemDataSourceDescriptor().getDataSourceName();
                   DataSource ds = (DataSource) cxt.lookup("jdbc/" + lookUpName);
                   ds.setLoginTimeout(60);
                   conn = ds.getConnection();...
    and I close connections like these
                            conn = db.getDefaultDatabaseConnection();
                   if (conn != null) {
                        try {
                             conn.setAutoCommit(true);
                             String sql = "INSERT INTO
                             pstmt.close();
                             conn.close();
                        } catch (Exception e) {
                                     } finally {
                             try {
                                  pstmt.close();
                                  conn.close();
                             } catch (SQLException e2) {
                                  e.printStackTrace();
                             e.printStackTrace();
    I changed system DataSource's   and i give these parameters
    Initial Connections: 5
    Maximum Connections: 125
    Maximum Time to Wait for Connection: 90
    Connection Lifetime (Sec.): 60
    Cleanup Interval (Sec.) : 90
    it didn't work either
    Can anyone hepl me  ?

    I would like to make slight changes in code. . Please close the resources only in finally block.
    Dont know you are closing resultset or not. If not, you must close it
    conn = db.getDefaultDatabaseConnection();
    try {
    if (conn != null) {
    conn.setAutoCommit(true);
    String sql = "INSERT INTO
    } catch (Exception e) {
    } finally {
        try{ 
           if(rs != null){
            rs.close()
         }catch(SqlException se){
            //log it  
       try{
           if(stmt != null){ 
                stmt.close();
         }catch(SqlException se){
            //log it
      try{
       if(conn != null){
         conn.close();
    } catch(SQLException ss){
      // log it
    } // end of finally
    Hope this help.

  • Java.sql.SQLException:Exhausted Resultset

    Hi,
    I am Getting java.sql.SQLException:Exhausted Resultset after filling up the form and clicking submit button so that values inserted in to Database but instead of insertion iam getting this error.
    ThankQ
    Regards
    Saikishore

    You are trying to call a closed resultset.
    check your code. if u don't find then post your relavant code
    (Dhananjay Singh)

  • "Exausted resultSet" error in servlet calling SQLJ

    I've got a servlet wich calls a sqlj methode; the sqlj opens an iterator, converts it as a resultset, and sends it to the servlet.
    Then, the servlet browses this ResultSet (with rs.next()) and output the data to screen.
    I don't know why, but sometimes, all data appears on the screen, and sometimes i get an error message "Exausted resultSet", and sometimes i get an other error message "Closed ResultSet".
    I use the same program, i just run it many times, and sometimes it crashes, and sometimes not. (and it don't crashe in the same moment)
    i use Tomkat 3.2.1 with apache
    where does this bug come from ? Tomkat or SQLj ??
    i've notice that the error appears when the garbage collector runs. If i run it manualy in the "while(rs.next())", it crashes immediately
    if i run the garbage collector before the "while" statement, for small resulset, it never crashes, but for bigger resultset it do ! (as if the problem appears when the garbage collector runs)
    it causes big problems to continue developping our application, so any help would be very appreciated...

    Are you using JDK 1.2.1? If yes, then try to use JDK 1.2.2 instead. We have seen JDK 1.2.1 garbage collecting things that are still in scope (very unsafe).
    If wiggling your configuration does not help, you'll need to provide more info about your environment and it would be best to get a reproducible test case.
    One other note: make sure to finally close the SQLJ iterator not the result set that is being returned. Otherwise you can start leaking cursor handles and/or statement cleanup will not be properly performed.

  • Closing data connection

    My program connects to a SQL database that I connect to on port 23 because outgoing connections to port 3306 are blocked from work.
    In my Database class I have this:
    public static Connection sqlConnection ()
            Connection connection = null;
            String serverName = null;
            String mydatabase = null;
            String url = null;
            String dbuser = null;
            String dbpass = null;
            String port = "23";
            try
                System.out.println ("Trying port " + port + "...");
                String driverName = "com.mysql.jdbc.Driver";
                Class.forName (driverName);
                serverName = "server_address";
                mydatabase = "database";
                url = "jdbc:mysql://" + serverName + ":" + port +  "/" + mydatabase;
                //url = "jdbc:mysql://" + serverName + "/" + mydatabase; // a JDBC url
                dbuser = "user";
                dbpass = "pass";
                connection = DriverManager.getConnection (url, dbuser, dbpass);
            catch (SQLException e)
                // Could not connect to the database
                JOptionPane.showMessageDialog (null,"<b>Unable to connect to the database.</b>\n\nPlease check your network connection."
                        + "Contact the administrator if the problem persists.", "Connection Error",
                        JOptionPane.ERROR_MESSAGE);
                System.out.println ("Error: " + e.getMessage ());
            catch (ClassNotFoundException e)
                // Could not find the database driver
                System.out.println ("Error: " + e.getMessage ());
                JOptionPane.showMessageDialog (null,"Could not find the database driver.", "Connection Error",
                        JOptionPane.ERROR_MESSAGE);
            return connection;
        }From my other classes I call the connection by using:
    Connection connection = Database.sqlConnection ();and close my connection with:
    connection.close (); System.out.println ("Connection closed.");This way in my console I can see when the connection is opening and closing.
    run:
    java.awt.Dimension[width=0,height=0]
    Trying port 23...
    6
    Tristan Lee
    [email protected]
    1
    2
    0
    2
    0
    Connection closed.
    Trying port 23...
    Connection closed.
    Trying port 23...
    Connection closed.
    Trying port 23...
    Connection closed.
    Trying port 23...
    Connection closed.When I use netstat to view my current connections, they still show a connection that, to me, looks like a connection that's staying open until it simply times out.
    [tristan@tristan ~]$ netstat
    Active Internet connections (w/o servers)
    Proto Recv-Q Send-Q Local Address               Foreign Address             State
    tcp        0    115 192.168.1.110:59820         205.188.9.53:aol            ESTABLISHED
    tcp        0      0 192.168.1.110:39436         64.12.31.96:aol             ESTABLISHED
    tcp        0    280 192.168.1.110:60949         cs8.msg.dcn.yahoo.com:mmcc  ESTABLISHED
    tcp        0     70 192.168.1.110:40097         by1msg5276706.phx.gbl:msnp  ESTABLISHED
    tcp        0      0 192.168.1.110:49336         oam-m07b.blue.aol.com:aol   ESTABLISHED
    tcp        0      0 ::ffff:192.168.1.110:43641  cpe-24-95-42-77.colu:telnet TIME_WAIT
    tcp        0      0 ::ffff:192.168.1.110:60616  cpe-24-95-42-77.colu:telnet TIME_WAIT
    tcp        0      0 ::1:36998                   ::1:38330                   TIME_WAIT
    tcp        0      0 ::ffff:192.168.1.110:51197  cpe-24-95-42-77.colu:telnet TIME_WAIT
    tcp        0      0 ::ffff:192.168.1.110:53461  cpe-24-95-42-77.colu:telnet TIME_WAIT
    tcp        0      0 ::ffff:192.168.1.110:37406  cpe-24-95-42-77.colu:telnet TIME_WAITWhy aren't my connections being closed?

    I know port 23 is for Telnet. The program runs at work and accesses a MySQL database from my house. Because I can't connect to port 3306 from work, Telnet connections are allowed so my program uses port 23 which my router forwards to port 3306 of my server, which works.
    I changed my code a bit because I noticed that I'm not closing my ResultSets, Statements, and PreparedStatements. Now I have the following in my Database class:
    public static void closeConnection (Connection connection)
            try
                connection.close ();
            catch(Exception e)
                System.out.println("Error closing connection:\n\n" + e);
        public static void closeStatement (Statement stmt)
            try
                stmt.close ();
            catch(Exception e)
                System.out.println("Error closing statement:\n\n" + e);
        public static void closePreparedStatement (PreparedStatement pstmt)
            try
                pstmt.close ();
            catch(Exception e)
                System.out.println("Error closing PreparedStatement:\n\n" + e);
        public static void closeResultSet (ResultSet rs)
            try
                rs.close ();
            catch(Exception e)
                System.out.println("Error closing ResultSet:\n\n" + e);
        }And then in my blocks where I'm connecting to the database I am using the following to close the connections:
                    Database.closeResultSet (rs);
                    Database.closePreparedStatement (pstmt);
                    Database.closeStatement (stmt);
                    Database.closeConnection (connection);
                    System.out.println ("Connection closed.");Does this look better?

Maybe you are looking for

  • User Exit in ME22N with version management

    Hi Experts,   I have implemented the userexit MM06E005 with FM - EXIT_SAPMM06E_012 . and in Include program i have given the code. CASE sy-tcode. when 'ME22N'. IF SY-UCOMM = 'MECHECKDOC' or sy-ucomm = 'MESAVE'.   If i_ekko-PROCSTAT = '01'.      messa

  • Search in Google no Longer works--still

    Although it is visible, when I select text and choose "Search in Google" from within an e-mail, nothing happens. This holds true for both my imap and smtp accounts. Safari does not open, nor Firefox. I have tried setting and resetting my preferred br

  • How do I hide my email and ip address from a website?

    I am on a simple free fan oriented college sports team opt in website, and I keep getting booted because I posted a picture in the comments section - totally PG. The moderator is being a punk and keeps booting me after two days no matter what differe

  • Song List Out of Whack

    I know there are several posts here that express the same issue, but I cannot find any definitive resolution, so I will ask the question again. iPhone 3Gs, iOS 4.2.1, in the iPod application, the list of songs and artists does not line up correctly w

  • Web Service without WSDL

    I have an existing web site that utlizes XML/XSQL extensively. What is an easy way of defining a WSDL for each of these XSQL pages?