Why should we have to close the result set and statement

I am told that , I have to close my connection , result set , statement objects in finally block.
why we need to do this ?
If close the connection wont it be sufficient?

To ensure that resources are freed in the client and in the database server.
Yes, closing the connection is enough. Except if you are a bit paranoid about broken JDBC drivers that don't close dependent resources properly - but I haven't seen such drivers in real life.
One important reason why programmers close ResultSets and Statements is that they use connection pools. In that case the Connection is returned to the pool instead of closing it. It is good practice to close RS's and Statements in preparation for the day when you graduate to writing code where you too will want to use a connection pool instead of the sloooooow reconnect-close-reconnect-close-etc.

Similar Messages

  • Why to need close the result set and statement

    why to need close the result set and statement

    It's best to explicitly close every ResultSet, Statement, and Connection in the narrowest scope possible.
    These should be closed in a finally block.
    Since each close() method throws SQLException, each one should be in an individual try/catch block to ensure that a failure to close one won't ruin the chances for all the others.
    You can capture this in one nice utility class, like this:
    package db;
    import java.sql.*;
    import java.util.ArrayList;
    import java.util.Map;
    import java.util.LinkedHashMap;
    import java.util.List;
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    * Created by IntelliJ IDEA.
    * User: MD87020
    * Date: Feb 16, 2005
    * Time: 8:42:19 PM
    * To change this template use File | Settings | File Templates.
    public class DatabaseUtils
         * Logger for DatabaseUtils
        private static final Log logger = LogFactory.getLog(DatabaseUtils.class);
        /** Private default ctor to prevent subclassing and instantiation */
        private DatabaseUtils() {}
         * Close a connection
         * @param connection to close
        public static void close(Connection connection)
            try
                if ((connection != null) && !connection.isClosed())
                    connection.close();
            catch (SQLException e)
                logger.error("Could not close connection", e);
         * Close a statement
         * @param statement to close
        public static void close(Statement statement)
            try
                if (statement != null)
                    statement.close();
            catch (SQLException e)
                logger.error("Could not close statement", e);
         * Close a result set
         * @param rs to close
        public static void close(ResultSet rs)
            try
                if (rs != null)
                    rs.close();
            catch (SQLException e)
                logger.error("Could not close result set", e);
         * Close both a connection and statement
         * @param connection to close
         * @param statement to close
        public static void close(Connection connection, Statement statement)
            close(statement);
            close(connection);
         * Close a connection, statement, and result set
         * @param connection to close
         * @param statement to close
         * @param rs to close
        public static void close(Connection connection,
                                 Statement statement,
                                 ResultSet rs)
            close(rs);
            close(statement);
            close(connection);
         * Helper method that maps a ResultSet into a map of columns
         * @param rs ResultSet
         * @return map of lists, one per column, with column name as the key
         * @throws SQLException if the connection fails
        public static final Map toMap(ResultSet rs) throws SQLException
            List wantedColumnNames = getColumnNames(rs);
            return toMap(rs, wantedColumnNames);
         * Helper method that maps a ResultSet into a map of column lists
         * @param rs ResultSet
         * @param wantedColumnNames of columns names to include in the result map
         * @return map of lists, one per column, with column name as the key
         * @throws SQLException if the connection fails
        public static final Map toMap(ResultSet rs, List wantedColumnNames)
            throws SQLException
            // Set up the map of columns
            int numWantedColumns    = wantedColumnNames.size();
            Map columns             = new LinkedHashMap(numWantedColumns);
            for (int i = 0; i < numWantedColumns; ++i)
                List columnValues   = new ArrayList();
                columns.put(wantedColumnNames.get(i), columnValues);
            while (rs.next())
                for (int i = 0; i < numWantedColumns; ++i)
                    String columnName   = (String)wantedColumnNames.get(i);
                    Object value        = rs.getObject(columnName);
                    List columnValues   = (List)columns.get(columnName);
                    columnValues.add(value);
                    columns.put(columnName, columnValues);
            return columns;
         * Helper method that converts a ResultSet into a list of maps, one per row
         * @param rs ResultSet
         * @return list of maps, one per row, with column name as the key
         * @throws SQLException if the connection fails
        public static final List toList(ResultSet rs) throws SQLException
            List wantedColumnNames  = getColumnNames(rs);
            return toList(rs, wantedColumnNames);
         * Helper method that maps a ResultSet into a list of maps, one per row
         * @param rs ResultSet
         * @param wantedColumnNames of columns names to include in the result map
         * @return list of maps, one per column row, with column names as keys
         * @throws SQLException if the connection fails
        public static final List toList(ResultSet rs, List wantedColumnNames)
            throws SQLException
            List rows = new ArrayList();
            int numWantedColumns = wantedColumnNames.size();
            while (rs.next())
                Map row = new LinkedHashMap();
                for (int i = 0; i < numWantedColumns; ++i)
                    String columnName   = (String)wantedColumnNames.get(i);
                    Object value = rs.getObject(columnName);
                    row.put(columnName, value);
                rows.add(row);
            return rows;
          * Return all column names as a list of strings
          * @param rs query result set
          * @return list of column name strings
          * @throws SQLException if the query fails
        public static final List getColumnNames(ResultSet rs) throws SQLException
            ResultSetMetaData meta  = rs.getMetaData();
            int numColumns = meta.getColumnCount();
            List columnNames = new ArrayList(numColumns);
            for (int i = 1; i <= numColumns; ++i)
                columnNames.add(meta.getColumnName(i));
            return columnNames;
    }Anybody who lets the GC or timeouts or sheer luck handle their resource recovery for them is a hack and gets what they deserve.
    Do a search on problems with Oracle cursors being exhausted and learn what the root cause is. That should convince you.
    scsi-boy is 100% correct.
    %

  • Firefox cannot open/reload any websites after resuming from a system standby. I have to close the current window and start a new session, then it works again

    I am using Firefox v 13.0.1 (Mozilla Firefox for Ubuntu canonical 1.0) on Ubuntu 12.04 LTS. Whenever my system resumes from standby I am not able to open/load any webpages in the Firefox session that was already running before the standby. I don't get any error message, but the page doesn't load at all. If I close the session and start a new one everything works fine.

    Not necessarily: rv:1.9.2.8 indicates a Firefox 3.6.8 version
    *Mozilla/5.0 (X11; Linux i686; rv:1.9.2.8) Gecko/20100722 Firefox/4.0.1
    You can check for a possibly corrupted user agent.
    See:
    *https://support.mozilla.org/kb/Finding+your+Firefox+version
    *https://support.mozilla.org/kb/websites-say-firefox-outdated-or-incompatible
    *http://kb.mozillazine.org/Resetting_your_useragent_string_to_its_compiled-in_default

  • Why can't I use the app that I bought with my Apple ID on my ipad & iphone? why should I have to buy the same app twice???

    Please answer my questions.
    Thanks

    of course I am logged in with the same id of me on both my devices. and when I go to app store, and then purchased apps, I only am able to see the other applications but not the one that I bought some hours ago. This happening now for the second time with me. the first time I bought one app using my iphone and then couldn't find it through ipad, and now it is the same reversely.
    Normally it shouldn'tbe like this! but i dont know what is going wrong.

  • Why do I have to close out of email and reopen it to check messages?

    Usually if I do not close out of an email session, when I go to check my messages later my mailboxes show a "!" symbol, indicating there is an issue; additionally, messages that I am trying to send do not go.  Once I close out and sign back in I am able to receive and send messages with no problem. 
    This is only on an issue when I am using the mail function on my iMac - not when I am checking from other computers; and
    This is not a password problem.  The only thing I need to do to receive messages is close and reopen the application - once I do that, messages are received (and sent) without problems.
    I don't recall if I have this issue when checking mail from me.com on my home computer or others, as I rarely check messages from there.
    I have an iMac 7.1 with OS 10.6.8 (not 10.4.11 as mistakenly checked off below).  This has been happening for several weeks, if not months, but since closing out and getting back into Mail was not a problem I haven't reported the issue until now.  Thank you very much for any assistance you can provide.

    Try using one of these extensions:
    Cookie Swap extension:
    https://addons.mozilla.org/firefox/3255/
    or
    Cookie Pie extension:
    http://www.nektra.com/oss/firefox/extensions/cookiepie/

  • Google search does not work. It does not bring back any results and disables my internet connection until I close the brower, wait, and then open it again.

    Google search does not work. It does not bring back any results and disables my internet connection. I have to close the browser, wait, and then open it again. It only seems to happen when I am signed into my Google account. If I am signed out the search functions properly.

    Do a malware check with some malware scanning programs on the Windows computer.<br />
    You need to scan with all programs because each program detects different malware.<br />
    Make sure that you update each program to get the latest version of their databases before doing a scan.<br /><br />
    *http://www.malwarebytes.org/mbam.php - Malwarebytes' Anti-Malware
    *http://www.superantispyware.com/ - SuperAntispyware
    *http://www.microsoft.com/security/scanner/en-us/default.aspx - Microsoft Safety Scanner
    *http://www.microsoft.com/windows/products/winfamily/defender/default.mspx - Windows Defender: Home Page
    *http://www.safer-networking.org/en/index.html - Spybot Search & Destroy
    *http://www.lavasoft.com/products/ad_aware_free.php - Ad-Aware Free
    See also:
    *"Spyware on Windows": http://kb.mozillazine.org/Popups_not_blocked

  • Can we open and close the cursor again and again

    hi all,
    with the help of cursor select statement i am writing some columns into the text file. while writing into the file in between i want to write something which belongs to others cursor. shall i close the first cursor and reopen it again..
    is its works?

    If you are using for loop the you don't need to open and close the cursor like:
    SQL> set autot off
    SQL> begin
      2     for i in (select ename, deptno, sal from emp)
      3     loop
      4             for j in (select dname from dept where deptno = i.deptno)
      5             loop
      6             dbms_output.put_line ('Ename:' || i.Ename ||'  Dept Name:'|| j.dname);
      7             end loop;
      8     end loop;
      9  end;
    10  /
    PL/SQL procedure successfully completed.
    SQL> set serveroutput on
    SQL> /
    Ename:SCOTT  Dept Name:RESEARCH
    Ename:first_0  Dept Name:SALES
    Ename:first_1  Dept Name:SALES
    Ename:first_0  Dept Name:RESEARCH
    Ename:first_1  Dept Name:SALES
    Ename:first_0  Dept Name:SALES
    Ename:first_1  Dept Name:ACCOUNTING
    Ename:first_0  Dept Name:RESEARCH
    Ename:first_1  Dept Name:ACCOUNTING
    Ename:first_0  Dept Name:SALES
    Ename:first_1  Dept Name:RESEARCH
    Ename:first_0  Dept Name:SALES
    Ename:first_1  Dept Name:RESEARCH
    Ename:first_0  Dept Name:ACCOUNTING
    PL/SQL procedure successfully completed.
    SQL> Or let us know about your requirements i.e. why you need to open/close the cursor again and again.

  • How can I use a Lookup task to lookup from my SQL Result set and have a join

    So in my Control Flow, I have an Execute SQL Task which gets my Table result set. I then have a Foreach Loop Container that iterates through the result set and a Data Flow. The first task in the Data Flow is an OLE DB Source SQL Command that retrieves data
    columns associated with my result set. I then do a Derived Column so I can SUBSTRING from one of my data columns and now I want to perform a Lookup to my Application Database.
    How do I code my Lookup task to utilize my SQL Result set variable and match on it? I cannot use the GUI for the Lookup task as my Lookup has to have some JOINS in it.
    Thanks for your review and am hopeful for a reply.

    Can you expand on that? I'm sorry but I am new and a novice to the SSIS world and I want to do this as best I can and as efficiently as I can. Are you saying that Rajen's way suggested above is the way to go?
    A little background....external data from a 3rd party client. I'v staged that external data to a SQL Server staging table. I have to try and match that data up to our database using SSN, DOB, and Gender...and if I can't match that way then I have to try
    and match by Name. I need to make sure that there is only one and only one account for that match. If I cannot match and match one and only one, then I'll create rows on a DataAnomaly Table. If I do match, then I have to check and make sure that there is only
    one and only one Member span for that match. Similarly handle the data anomaly and then check and make sure there is a "Diabetes" claim and similarly handle the DataAnomaly accordingly.
    That's where I'm at. Sooooo are you saying to use Rajen's suggestion? I don't think I can do that because I need multiple SQL tasks and I cannot connect multiple OLE DB Source tasks.
    Any help and suggestions are greatly appreciated.
    Thanks.

  • Help with streaming result sets and prepared statements

    hi all
    I create a callable statement that is capable of streaming.
    statement = myConn2.prepareCall("{call graphProc(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}",java.sql.ResultSet.TYPE_FORWARD_ONLY,
    java.sql.ResultSet.CONCUR_READ_ONLY);
    statementOne.setFetchSize(Integer.MIN_VALUE);
    the class that contains the query is instantiated 6 times the first class streams the results beautifully and then when the second
    rs = DatabaseConnect.statementOne.executeQuery();
    is executed I get the following error
    java.sql.SQLException: Can not use streaming results with multiple result statements
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:910)
    at com.mysql.jdbc.MysqlIO.readAllResults(MysqlIO.java:1370)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1688)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:3031)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:943)
    at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1049)
    at com.mysql.jdbc.CallableStatement.executeQuery(CallableStatement.java:589)
    the 6 instances are not threaded and the result set is closed before the next query executes is there a solution to this problem it would be greatly appreciated
    thanks a lot
    Brian

    Database resources should have the narrowed scope
    possible. I don't think it's a good idea to use a
    ResultSet in a UI to generate a graph. Load the data
    into an object or data structure inside the method
    that's doing the query and close the ResultSet in a
    finally block. Use the data structure to generate
    the graph.
    It's an example of MVC and layering.
    Ok that is my bad for not elaborating on the finer points sorry, the results are not directly streamed into the graphs from the result set. and are processed in another object and then plotted from there.
    with regards to your statement in the beginning I would like to ask if you think it at least a viable option to create six connections. with that said would you be able to give estimated users using the six connections under full usage.
    just a few thoughts that I want to
    bounce off you if you don't mind. Closing the
    statement would defeat the object of of having a
    callable statement How so? I don't agree with that.
    %again I apologise I assumed that since callable statements inherit from prepared statements that they would have the pre compiled sql statement functionality of prepared statements,well If you consider in the example I'm about to give maybe you will see my point at least with regards to this.
    The statement that I create uses a connection and is created statically at the start of the program, every time I make a call the same statement and thus connection is used, creating a new connection each time takes up time and resources. and as you know every second counts
    thanks for your thoughts
    Brian.

  • I keep getting a message that Firefox is open and not responding. That I have to close the Firefox application or restart my computer. A real pain. Why is the firefox application not closing in English

    I keep getting a message that Firefox is open and not responding. That I have to close the Firefox application or restart my computer. A real pain. Why is the firefox application not closing.

    Sounds like Firefox is "hanging at exit". That problem is frequently caused by an Extension or a Plugin. Read all of the following articles.<br /><br />
    NOTE: Establish a habit of exiting/closing Firefox with Firefox button > Exit or File > Exit to allow an orderly shutdown of Firefox and closing of all of the files that Firefox has open.
    #Stop the Firefox process:
    #*[http://kb.mozillazine.org/Kill_application Mozillazine - Kill application]
    #*Windows 7 users click [http://www.techrepublic.com/blog/window-on-windows/reap-the-benefits-of-windows-7s-task-manager/2576 here]
    #*Mac users: http://techheavy.com/2011/02/the-mac-task-manager/
    #Why Firefox may hang:
    #*[http://support.mozilla.org/en-US/kb/Firefox+hangs Firefox hangs] (see Hang at exit)
    #*[http://kb.mozillazine.org/Firefox_hangs Firefox hangs (Mozillazine)] (see Hang at exit and Closing Firefox properly)
    #*[https://support.mozilla.org/en-US/kb/Firefox+is+already+running+but+is+not+responding Firefox is already running but is not responding]
    #Use Firefox Safe Mode to find a problem with an Extension or Plugin:
    #*Don't check anything when entering Safe Mode, just continue
    #*If the problem does not occur in Safe Mode it is probably an Extension or Plugin causing the problem
    #*See:
    #**[[Safe Mode]] and [http://kb.mozillazine.org/Safe_Mode Safe Mode (Mozillazine)]
    #**[http://support.mozilla.org/en-US/kb/Troubleshooting+extensions+and+themes Troubleshooting extensions and themes]
    #**[http://support.mozilla.org/en-US/kb/Troubleshooting+plugins Troubleshooting plugins]
    #**[http://support.mozilla.org/en-US/kb/Basic+Troubleshooting Basic Troubleshooting]
    '''If this reply solves your problem, please click "Solved It" next to this reply when <u>signed-in</u> to the forum.'''
    Not related to your question, but...
    You may need to update some plug-ins. Check your plug-ins and update as necessary:
    *Plug-in check --> http://www.mozilla.org/en-US/plugincheck/
    *Adobe Shockwave for Director Netscape plug-in: [https://support.mozilla.org/en-US/kb/Using%20the%20Shockwave%20plugin%20with%20Firefox#w_installing-shockwave Installing ('''''or Updating''''') the Shockwave plugin with Firefox]
    *Adobe PDF Plug-In For Firefox and Netscape: [https://support.mozilla.org/en-US/kb/Using%20the%20Adobe%20Reader%20plugin%20with%20Firefox#w_installing-and-updating-adobe-reader Installing/Updating Adobe Reader in Firefox]
    *'''''Shockwave Flash''''' (Adobe Flash or Flash): [https://support.mozilla.org/en-US/kb/Managing%20the%20Flash%20plugin#w_updating-flash Updating Flash in Firefox]
    *'''''Next Generation Java Plug-in for Mozilla browsers''''': [https://support.mozilla.org/en-US/kb/Using%20the%20Java%20plugin%20with%20Firefox#w_installing-or-updating-java Installing or Updating Java in Firefox]

  • Pages and numbers will not take dictation and iOS 8. Very frustrating screen goes blank no keypad. I have to close the document In order to get rid of the big blank space where the keyboard should ber

    Pages and Numbers will not take dictation in iOS 8 on my iPad 4 and iPad mini.
    Very frustrating -screen goes blank where keyboard should be when I touch the microphone- no keypad & dictation does not record. I have to close the document In order to get rid of the big blank space where the keyboard should be. When is this going to be fixed?it's making recordkeeping Pages and Numbers,  which I use heavily, almost impossible.
    also dictation in other locations such as Mail put capitals in the middle of sentences and sometimes don't capitalize first letter in a sentence (see first letter of this sentence!) and other instances like the months of the year or the days of the week. Is anyone else having these problems?

    Pages and Numbers will not take dictation in iOS 8 on my iPad 4 and iPad mini.
    Very frustrating -screen goes blank where keyboard should be when I touch the microphone- no keypad & dictation does not record. I have to close the document In order to get rid of the big blank space where the keyboard should be. When is this going to be fixed?it's making recordkeeping Pages and Numbers,  which I use heavily, almost impossible.
    also dictation in other locations such as Mail put capitals in the middle of sentences and sometimes don't capitalize first letter in a sentence (see first letter of this sentence!) and other instances like the months of the year or the days of the week. Is anyone else having these problems?

  • Statement.close() Not closing the Result set

    Hi all,
    I have the following code which invokes a procedure in Oracle database
    public static callProcedure(Connection connection,String procedure){
    ResultSet resultSet = null;
    CallableStatement callableStatement = null;
    try {
    callableStatement = connection.prepareCall(procedure);
    callableStatement.registerOutParameter(1,OracleTypes.CURSOR);
    callableStatement.execute();
    resultSet =((OracleCallableStatement)callableStatement).getCursor(1);
    } catch (Exception exception) {
    exception.printStackTrace();
    } finally {
    try {
    callableStatement.close();
    } catch (SQLException sqlException) {
    sqlException.printStackTrace()
    return resultSet;
    Ideally if i try to iterate through the result set which is returned then it should give me resultset closed as i am closing the resultset. But this is not happening.
    Please anybody can explain the isue

    Hi,
    That is not easy to explain, I might take a guess and say that a statement cache is being used therefore the statement is not actually being closed.
    I always close the reultset then the statement so wouldn't notice this behaviour.
    Why are you returning a resultset anyway? If you really need to do this I would suggest using a disconnected resultset:
    OracleCachedRowSet ocrs = new OracleCachedRowSet();
    ocrs.populate(resultSet);
    return ocrs;

  • My wifi goes down at least once a day and I have to unplug the time capsule and reboot it and then it works fine.  Any idea why this is happening/what I can do to fix it?

    My wifi goes down at least once a day and I have to unplug the time capsule and reboot it and then it works fine.  Any idea why this is happening/what I can do to fix it?

    I was having this problem while still using Mavericks -- it started after a Mavericks update last spring.  During the initial Yosemite beta runs over the summer, it seemed to be fixed, but after the official launch in October, I had all sorts of problems keeping connected.  Its gotten a little better, but still happens to at least one of my devices every day.  Weird that we still cannot figure out why the connection keeps dropping on some devices, but not others, and then the next day, one of the devices that didn't disconnect the previous day will disconnect, but the ones that did disconnect, stay connected.  It's just sloppy, poorly written software for technology that isn't working the way it should.  If you turn off Continuity and Handoff on all your devices, you will probably see that everything stays connected.  With those turned off on all devices, TC stayed connected to everything for over a month.  The day I turned Continuity back on, all the problems started again.  It had something to do with the bluetooth version being used, the wifi routine, and Apple's AirPlay technology not quite getting along with each other.

  • Hi, i had created a form on adobe forms central,  but i don't have access to the results now.  any help would be appreciated.

    Hi, i had created a form on adobe forms central,  but i don't have access to the results now.  any help would be appreciated.

    Hi massif76198910,
    I don't see that you had a paid FormsCentral account. Were you using the free account? If so, you should still have access to the form until FormsCentral is retired on July 28 2015,
    Are you able to log in? Or do you get an error when you try to log in to your account? Please try clearing the browser cache, or logging in via a different browser.
    Best,
    Sara

  • When I click on "System services" it just stays highlighted and have to close the settings down

    I have been have problems with my Iphone5S battery life recently, I have followed the steps to save as much battery life as possible and I went to a genius bar as I thought the battery may be on its way out but they ran tests and told me its still a healthy battery, in the 90% mark and anything over 80% is good especially when I have had over 500 charges. They told me software errors and crashes have occured a lot and to complete a fresh install of IOS which I'm hoping i factory settings, which I have just completed yesterday and so the software is completely new. I have found that the battery has already decreased by 10% in 20 minutes without hardly any use, I wanted to go to system services and turn off certain services and it just freezes on this title when clicked on and I have to close the setttings app down double tapping the home button. Has anyone else noticed this issue and does anyone reccomend any advice, do I need a new battery etc?
    thankyou

    UPDATE
    I have solved the settings issue so the main issue is have I reset the phone correctly and should I replace my battery? thanks

Maybe you are looking for