Why should we close a connection

Hi,
Connection conn = DriverManager.getConnection (databaseUrl, userName, userPassword);
Why should we close a connection
conn.close();
Even when i give no "close command", it works !
Thank You
Edited by: ashipj on ?? ????????, ???? ?:?? ???????

My code frequently fetches data from database, so i created a class like this
public class ConnectToDatabase
/*             public ConnectToDatabase()
                                Connection conn;
     public ResultSet selectS(String userQuery) throws Exception
          String userName = "root";
          String userPassword = "gal";
          String databaseUrl = "jdbc:mysql://localhost:3306/test";
          Class.forName ("com.mysql.jdbc.Driver");
          Connection conn = DriverManager.getConnection (databaseUrl, userName, userPassword);
          String query = userQuery;
          Statement S=conn.createStatement();
          ResultSet RS=S.executeQuery(query);
                                //conn.close;
          return RS;
                                //conn.close;
/*              public void closeConnection()
                                conn.close;
}and from the main code i make call as given below (it works fine)
ConnectToDatabase CTD=new ConnectToDatabase();
ResultSet result=CTD.selectS(String userQuery);
//CTD.closeConnection();Now my problem is
1) If try to give "conn.close()" before "return RS;" It will show error (RS cannot be fetched after closing connectio)
2) If write conn.close after return it wont be executed (ofcourse - unreachable statement)
3) If use "CTD.closeConnection();" it gives errror saying that "cannot find conn(in closeConnection()) " i dont know why constructor is noy loaded.

Similar Messages

  • Why should we have to connect to jdbc rather directly connecting to odbc?

    Why should we have to connect to jdbc rather directly connecting to odbc.why there should be a bridge?

    sandy,
    The short answer is: because it should.
    The long answer is: bb-ee-cc-aa-uu-ss-ee  ii-tt  ss-hh-oo-uu-ll-dd.
    The really long answer is: JDBC is portable. ODBC isn't... It's yet another Microshite-locked-down psuedo-open technology... So go implement an ODBC driver (in pure java please) if the concept gives you wood.
    Or just just use the jdbc/odbc bridge (if you must) like the rest of us.
    Cheers. Keith.

  • Once I install lates Adobe flash player why should I close internet explorer and why I to reapeat ?

    My problem with Adobe Flash player installation is two fold : 1- I have to close internet expl;orer every time  after it was installed  already ?
    2- Why I have to repeat the installation when another window opens and you requitre another installation ? Why _ Why ?

    Do you see the animation and version displayed when you visit this page?
    Flash Player Version
    Do you see something similar to this screenshot when visiting this page?
    http://www.bobbyvandersluis.com/swfobject/testsuite_2_2/test_dynamic_multiple.html

  • When and How to close database connection in JSP?

    Hi there,
    I am using MySQL and JDBC 3.0, in my system, When and How to close database connection in JSP?
    Thanks in advance.
    Lonely Wolf
    <%@ page session="true" language="java" %>
    <jsp:include page="checkauthorization.jsp" />
    <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
    <%@ taglib prefix="sql" uri="http://java.sun.com/jstl/sql" %>
    <%--
    Execute query, with wildcard characters added to the
    parameter values used in the search criteria
    --%>
    <sql:query var="availablecomputerList" dataSource="jdbc/Bookingcomputer" scope="request">
    SELECT * FROM computer where status=0
    order by s_code
    </sql:query>
    <html>
    <head>
    <title>Search Result</title>
    </head>
    <body bgcolor="white">
    <center>
    <form action="checkin.jsp" method="post">
    <input type="submit" value="Back to Check-in Page">
    </form>
    <c:choose>
    <c:when test="${availablecomputerList.rowCount == 0}">
    Sorry, no available computer found.
    </c:when>
    <c:otherwise>
    The following available computers were found:
    <table border="1">
    <th>Computer</th>
    <th>Description</th>
    <th>Status</th>
    <c:forEach items="${availablecomputerList.rows}" var="row">
    <tr>
    <td><c:out value="${row.s_code}" /></td>
    <td><c:out value="${row.description}" /></td>
    <td><c:out value="${row.status}" /></td>
    </tr>
    </c:forEach>
    </table>
    </c:otherwise>
    </c:choose>
    </center>
    </body>
    </html>

    when should you close the connection? when you're done with it.
    how should you close the connection? like this: conn.close();
    that said, doing this in a JSP page is bad form and not recommended
    JSP's typically don't contain ANY business or data logic

  • When to close database connections

    Hi Guys
    If a user logs in I create a new DB connection and verify his password etc. Once verified I store his details in a session bean. Now, should I close the connection or leave it open so I can continue to use it later on in other servlets?

    -Kayaman- wrote:
    BigDaddyLoveHandles wrote:
    You are using connection pooling, eh?Well I am, and he'll be using too eventually. Even without connection pooling it's not a good idea to keep connections open for long periods of times.Indeed, but the OP used the phrase "new connection" in his question, where I would have written, "a connection from the pool".

  • 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.

  • So my phone a 4s is less than two years old, the speakers do not work, and it will not connect to wi-fi, so my question is on the 1st of august why should I re-up my contract and purchase a phone that taken care of did not last the distance of a contract?

    So my phone a 4s is less than two years old, the speakers do not work, and it will not connect to wi-fi, so my question is on the 1st of august why should I re-up my contract and purchase a phone that taken care of did not last the distance of a contract?

    This is a user to user technical support forum.  It is not our responsibility to convince you of anything.
    Do you actually have a technical support question?  If not, post your question on a blog or somewhere more appropriate.
    Best,
    GDG

  • Why is my ipod saying 'iPod is disabled, connect to itunes' when i try connecting it to itunes, it comes up with this pop up saying it couldn't take my ipod because it has a passcode on it?, why should i connect it when it doesn't even take it!!!

    Why is my ipod saying 'iPod disabled, connect to itunes' when i try connecting it to itunes, it comes up with this pop up saying it couldn't take my ipod because theres a passcode on it?, why should i connect it when it doesn't even take it!!!

    Follow ALL  the Steps in this article  >  http://support.apple.com/kb/HT1808
    You may have to try it more than once...

  • Trying to send using Apple mail program after installing Mavericks; Keep getting box "iCloud Cannot connect to account iCloud". Entering password restores mail but why should  I have to do this?

    Trying to send mail via Apple's email program (not iCloud off web page)  after Mavericks show pane "iCloud cannot connect to account iCloud". Entering p/w restores mail but why should this be happening?

    While I am no fan of Best Buy and would not buy a lightbulb from them I doubt you issues have anything to do with your iMac and more to do with your lack of experience and simply getting bad advice. Judging by you post I suspect you have loaded your computer down with a lot of crapware and that  has caused it's problems. For example running antivirus apps on a Mac not only is a waste of time, it's a waste of money, system resources and will eventually create more problems that it solves. Please begin educating yourself on the subject by reading Thomas Reeds articles on the subject, Thomas is a frequent and knowledgeable contributor to these forums. You can find his webpage at http://www.reedcorner.net/tech-guides/
    The good news is here are absolutely no, zero, zippo viruses for OS X. There are other types of malware available (for example trojans) however they differ greatly from viruses in that the use has to download and install them, whereas viruses do not work that way. OS X is not like MS Windows and is extremely secure.
    My suggestion at this point would be to clean your computer of the crapware (including antivirus apps) however before doing so please download and install EtreCheck and post its report. Then we can see how your computer has been configured and begin to give you some advice on the next steps.

  • 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.
    %

  • Do I close my connection yet? How to improve it

    Hi all,
    my connection pool is not working well, the connection is not release back to pool. why??
    package formate;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    import javax.sql.*;
    import pool.ConnectionPool;
    * TryJdbc.java
    * This servlet demonstrates using JDBC
    public class Formate extends HttpServlet {
       Statement stmt =null;
        ResultSet rs = null;
        Connection conn = null;
      ConnectionPool connectionPool = null;
    * Creates a connection pool.
    public void init() throws ServletException
    String jdbcDriver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
    String dbURL ="jdbc:microsoft:sqlserver://localhost:1433; DatabaseName=sequences";
    try
    //instantiate the connection pool object by passing the
    //jdbc driver, database URL, username, and password
    connectionPool = new ConnectionPool(jdbcDriver, dbURL,
    "A#$","RE@89");
    //specify the initial number of connections to establish
    connectionPool.setInitialConnections(5);
    //specify number of incremental connections to create if
    //pool is exhausted of available connections
    connectionPool.setIncrementalConnections(5);
    //specify absolute maximum number of connections to create
    connectionPool.setMaxConnections(20);
    connectionPool.createPool(); //create the connection pool
    catch(Exception e)
    System.out.println("Error: " + e);
    }in my doget I have
    conn = connectionPool.getConnection();
         stmt = conn.createStatement();
    ...query
    finally {
    try {
    if(rs != null)
    rs.close();
    rs = null;
    if(stmt != null)
    stmt .close();
    stmt = null;
    if(conn != null)
    conn.close();
    conn = null;
    connection.returnConnection(conn); }
    package pool;
    import java.sql.*;
    import java.util.*;
    public class ConnectionPool
    private String jdbcDriver = "";
    private String dbUrl = "";
    private String dbUsername = "";
    private String dbPassword = "";
    private int initialConnections = 10;
    private int incrementalConnections =5;
    private int maxConnections = 50;
    private Vector connections = null;
    * Constructor stores the parameters passed by the calling
    * object.
    * @param jdbcDriver String containing the fully qualified name
    * of the jdbc driver (class name and full package info)
    * @param dbUrl String containing the database URL
    * @param dbUsername String containing the username to use when
    * logging into the database
    * @param dbPassword String containing the password to use when
    * logging into the database
    public ConnectionPool(String jdbcDriver, String dbUrl,
    String dbUsername, String dbPassword)
    this.jdbcDriver = jdbcDriver;
    this.dbUrl = dbUrl;
    this.dbUsername = dbUsername;
    this.dbPassword = dbPassword;
    * Returns the initial number of connections to create.
          * @return Initial number of connections to create.
    public int getInitialConnections()
    return initialConnections;
          * Sets the initial number of connections to create.
    * @param initialConnections Initial number of connections to
    * create
    public void setInitialConnections(int initialConnections)
    this.initialConnections = initialConnections;
    * Returns the number of incremental connections to create if
    * the initial connections are all in use.
    * @return Number of incremental connections to create.
    public int getIncrementalConnections()
    return incrementalConnections;
    * Sets the number of incremental connections to create if
    * the initial connections are all in use.
    *@param incrementalConnections Number of incremental
    * connections to create.
    public void setIncrementalConnections(
    int incrementalConnections)
    this.incrementalConnections = incrementalConnections;
    * Returns the absolute maximum number of connections to
          * create. If all connections are in use, the getConnection()
    * method will block until one becomes free.
    * @return Maximum number of connections to create.
    public int getMaxConnections()
    return maxConnections;
    * Sets the absolute maximum number of connections to create.
    * If all connections are in use, the getConnection() method
    * will block until one becomes free.
    * @param maxConnections Maximum number of connections to
    * create.
    public void setMaxConnections(int maxConnections)
    this.maxConnections = maxConnections;
    * Creates a pool of connections. Number of connections is
    * determined by the value of the initialConnections property.
    public synchronized void createPool() throws Exception
    //make sure that createPool hasn't already been called
    if (connections!=null)
    return; //the pool has already been created, return
    //instantiate JDBC driver object from init param jdbcDriver
    Driver driver = (Driver)
    (Class.forName(jdbcDriver).newInstance());
    DriverManager.registerDriver(driver); //register JDBC driver
    connections = new Vector();
    //creates the proper number of initial connections
    createConnections(initialConnections);
    * Creates the specified number of connections, places them in
    * a PooledConnection object, and adds the PooledConnection to
    * the connections vector.
    * @param numConnections Number of connections to create.
    private void createConnections(int numConnections) throws
    SQLException
    //create the specified number of connections
    for (int x=0; x < numConnections; x++)
    //have the maximum number of connections been created?
    //a maxConnections value of zero indicates no limit
    if (maxConnections > 0 &&
    connections.size() >= maxConnections)
    break; //break out of loop because we're at the maximum
    //add a new PooledConnection object to connections vector
    connections.addElement(new PooledConnection(
    newConnection()));
    System.out.println("Database connection created...");
    * Creates a new database connection and returns it.
    * @return New database connection.
    private Connection newConnection() throws SQLException
    //create a new database connection
    Connection conn = DriverManager.getConnection (dbUrl,
    dbUsername, dbPassword);
    //if this is the first connection, check the maximum number
    //of connections supported by this database/driver
    if (connections.size()== 0)
    DatabaseMetaData metaData = conn.getMetaData();
    int driverMaxConnections = metaData.getMaxConnections();
    //driverMaxConnections value of zero indicates no maximum
    //or unknown maximum
    if (driverMaxConnections > 0 &&
    maxConnections > driverMaxConnections)
    maxConnections = driverMaxConnections;
    return conn; //return the new connection
    * Attempts to retrieve a connection from the connections
    * vector by calling getFreeConnection(). If no connection is
    * currently free, and more can not be created, getConnection()
    * waits for a short amount of time and tries again.
    * @return Connection object
    public synchronized Connection getConnection()throws
    SQLException
    //make sure that createPool has been called
    if (connections == null)
    return null; //the pool has not been created
    Connection conn = getFreeConnection();//get free connection
    while (conn == null) //no connection was currently free
    //sleep for a quarter of a second and then check to see if
    //a connection is free
    wait(250);
    conn = getFreeConnection(); //try again to get connection
    return conn;
    * Returns a free connection from the connections vector. If no
    * connection is available, a new batch of connections is
    * created according to the value of the incrementalConnections
    * variable. If all connections are still busy after creating
    * incremental connections, the method will return null.
    * @return Database connection object
    private Connection getFreeConnection() throws SQLException
    //look for a free connection in the pool
    Connection conn = findFreeConnection();
    if (conn == null)
    //no connection is free, create additional connections
    createConnections(incrementalConnections);
    //try again to find a free connection
    conn = findFreeConnection();
    if (conn == null)
    //there are still no free connections, return null
    return null;
    return conn;
    * Searches through all of the pooled connections looking for
    * a free connection. If a free connection is found, its
    * integrity is verified and it is returned. If no free
    * connection is found, null is returned.
    * @return Database connection object.
    private Connection findFreeConnection()throws SQLException
    Connection conn = null;
    PooledConnection pConn = null;
    Enumeration enum = connections.elements();
    //iterate through the pooled connections looking for free one
    while (enum.hasMoreElements())
    pConn =(PooledConnection)enum.nextElement();
    if (!pConn.isBusy())
    //this connection is not busy, get a handle to it
    conn = pConn.getConnection();
    pConn.setBusy(true); //set connection to busy
    //connection is no longer valid, create a new one
    conn = newConnection();
    //replace invalid connection with new connection
    pConn.setConnection(conn);
    break; //we found a free connection, stop looping
    return conn;
    * Test the connection to make sure it is still valid. If not,
    * close it and return FALSE.
    * @param conn Database connection object to test.
    * @return True indicates connection object is valid.
    * Turns off the busy flag for the current pooled connection.
    * All ConnectionPool clients should call returnConnection() as
    * soon as possible following any database activity (within a
    * finally block).
    * @param conn Connection object
    public void returnConnection(Connection conn)
    //make sure that createPool has been called
    if (connections== null)
    return; //the pool has not been created
    PooledConnection pConn = null;
    Enumeration enum = connections.elements();
    //iterate through the pooled connections looking for the
    //returned connection
    while (enum.hasMoreElements())
    pConn =(PooledConnection)enum.nextElement();
    //determine if this pooled connection contains the returned
    //connection
    if (conn == pConn.getConnection())
    //the connection has been returned, turn off busy flag
    pConn.setBusy(false);
    break;
    * Refreshes all of the connections in the connection pool.
    public synchronized void refreshConnections()throws
    SQLException
    //make sure that createPool has been called
    if (connections == null)
    return; //the pool has not been created
    PooledConnection pConn = null;
    Enumeration enum = connections.elements();
    while (enum.hasMoreElements())
    pConn =(PooledConnection)enum.nextElement();
    if (!pConn.isBusy())
    wait(10000); //wait 5 seconds
    closeConnection(pConn.getConnection());
              pConn.setConnection(newConnection());
              pConn.setBusy(false);
    * Closes all of the connections and empties the connection
    * pool. Once this method has been called, the createPool()
    * method can again be called.
    public synchronized void closeConnections() throws SQLException
    //make sure that createPool has been called
    if (connections == null)
    return; //the pool has not been created
    PooledConnection pConn = null;
    Enumeration enum = connections.elements();
    while (enum.hasMoreElements())
    pConn = (PooledConnection)enum.nextElement();
    if (!pConn.isBusy())
    wait(5000); //wait 5 seconds
    closeConnection(pConn.getConnection());
    connections.removeElement(pConn);
    connections = null;
    * Closes a database connection.
    * @param conn Database connection to close.
    private void closeConnection(Connection conn)
    try
    conn.close();
    catch (SQLException e)
    * Sleeps for a specified number of milliseconds.
    *@param mSeconds Number of seconds to sleep.
    private void wait(int mSeconds)
    try
    Thread.sleep(mSeconds);
    catch (InterruptedException e)
    * Inner class encapsulating the properties of a pooled
    * connection object. These properties include a JDBC database
    * connection object and a flag indicating whether or not the
    * database object is currently in use (busy).
    class PooledConnection
    Connection connection = null;
    boolean busy = false;
    public PooledConnection(Connection connection)
    this.connection = connection;
    public Connection getConnection()
    return connection;
    public void setConnection(Connection connection)
    this.connection = connection;
    public boolean isBusy()
    return busy;
    public void setBusy(boolean busy)
    this.busy = busy;
    }thank you

    If you are using connection pooling then those places in your code where you used to close a connection need to be replaced by code that returns the connection to the pool.
    It's the job of the pool implementation to decide whether or not connections need closing (or opening), depending on the rules you set up for the pooler.

  • Properly close database connection - Oracle

    I have an unusuall application that has a main in it and runs off of a cron job.
    We have orders that have to be filled, and if the approver of that order does not reject it after 30 minutes its automatically filled.
    The weird thing is that alot of these stored procedures were already in place before I got there so I just went ahead and called them to get the data that I needed.
    So, we have a shell script that just calls my class. The main kicks off and gets the time of the orders placed on that day. If the current time minus the time the order was placed is greater than 30 minutes approve the order.
    Now, I have about 3 - stored procedures that I call in one method. Actually I have about 3 or 4 methods that in turns calls these stored procedures. I have callable statements for each method. and I do a try - catch in each of the other methods, but not a connection close. In the one method that does all the work and calls the other methods, I have a try - catch - and a then a finally. I then do a conn.close() in the finally of this method.
    My question is? Is this correct. Should I do a try catch finally in my main() method.
    So, this is sort of what it looks like.
    class DoSomething
       Connection conn;
       method1()
          try
             CallableStatement cs;
             ResultSet rs;
             rs.close;
             cs.close;
          catch
          return something1;
       method2()
          try
             CallableStatement cs;
             ResultSet rs;
             rs.close;
             cs.close;
          catch
          return Something2;
       method3()
          try
             CallableStatement cs;
             ResultSet rs;
             rs.close;
             cs.close;
          catch
          return Something3;
       doSomethingMethod()
          try
             CallableStatement cs;
             ResultSet rs;
            // call the other methods to get all data needed.
            ds.method1;
            ds.method2;
            ds.method3;
             rs.close;
             cs.close;
          catch
          finally
              conn.close();
       main()
          DoSomething ds = new DoSomething();
          ds.doSomethingMethod();
    }orozcom

    Well, The catch blocks are not empty. I assure you. I
    just didn't feel like writing down all of my code.
    plus I did not want to cloud the example with to much
    code. Very good.
    All I wanted to know is when and where to close
    my resultset, callable statements, and connection.OK, you should close each one in its own individual try/catch block in a finally block inside the method in which they were called.
    If the stored procs are a unit of work, you'll have to share the Connection.
    Please also realize that this is a web based
    application as well. I take in parameters from a URL.
    I pass those parameters to the stored procs (which
    are already there). If you're doing that in a JSP, I'd say you've got a bad design.
    Now sometimes one method needs
    information from another method. So, I run that
    method. pass the info to another method or stored
    proc which gives me my info. All this should be happening in a service layer.
    I was told that a finally block always runs. So, I
    thought if I atleast put my conn.close in the
    finally. then it will always close the connection.As long as it doesn't throw an exception. And you should close ResultSets and Statements, regardless of what the javadocs say.
    Also, there is only one database that I call. Now the
    stored procs are all on the same database, but they
    are in different packages. which is why I use the
    callable statements.That's fine.
    Also, I do not only call stored procs. I usually only
    call a stored proc to get information back, and then
    give it to a class to manipulate the data.Sounds inefficient. Would a JOIN do as well? You might fall into the (n+1) query trap, where you run a query to get a ResultSet and then iterate through it and run another query per iteration. This is inefficient as n gets large.
    %

  • When to open and close database connection

    im trying to connect to a oracle database using servlets
    when should i open and close the connection
    it works fine when i do both in the doPost() method
    but when i tried to open connection in init() methd .. it doesnt seem to work
    what should i do...
    the connection is initialised in the init() method but is null in the doPost() method

    " im trying to connect to a oracle database using servlets
    when should i open and close the connection
    it works fine when i do both in the doPost() method
    but when i tried to open connection in init() methd .. it doesnt seem to work
    what should i do...
    the connection is initialised in the init() method but is null in the doPost() method"
    1:
    without seeing the code i would say the the connection is null
    because you are storing it as a servlet class variable which is
    not thread safe.
    2:
    The best way to do it using connection pooling
    detailed docs on the tomcat website
    3:
    if you are not using connection pooling, then
    open and close the connection in the do* method
    or
    use init() to place the connection in the servletconfig
    and close in destroy() and use synching to access

  • Why does Apple iPad Camera Connection Kit no longer work with iOS8

    Why does Apple iPad Camera Connection Kit no longer work with iOS8?

    The kit is firmly inserted in thhe iPad's dock ? You could also try a reset and see if it's recognised after the iPad has restarted : press and hold both the sleep and home buttons for about 10 to 15 seconds (ignore the red slider), after which the Apple logo should appear - you won't lose any content, it's the iPad equivalent of a reboot.
    I haven't had problems using the kit with SD cards from Canon cameras . What capacity is the card, and it's an SD or SDHC card - if it's an SDXC card that's formatted as ExFAT then it won't be recognised

  • HT5012 Why should I click the accept button for a server certificate at every initial time although it is listed as a trusted root CA on iOS6?

    I'm now using a root CA which was listed above.
    But when I try to connect WLAN via EAP with RADIUS initially, I should click the accept button for the certificate of the RADIUS Server.
    Why should it work?

    Hi,
    I'm still looking for the reason.
    Isn't there any way which can avoid the verification for a public certificate of authentication server using EAP-TLS.
    Why should I click the accept button in initial step for authenticating with RADIUS server using EAP-TLS although the root CA of the server certificate is listed in the default trusted CA on iOS?

Maybe you are looking for

  • How can we Assign Multiple DS to Cube

    Hi can you any tell me how to load data from multiple data sources to one Target. Ex:- I have Sales,Delivery, Billing Data Sources. I want to add these Data Sources to sales over cube.Will it works.Other wise you can share your Solutions.

  • HT1338 Black/Noise-swirl display issue on Mac Mini late 2012

    I have been getting Black/Noise-swirl display cut-outs lasting up to 3 seconds, occuring about twice a day. Hardware: i7 Quad-core Mac Mini (L2012), 4GbRam, 1tb HardDrive - currently using the Apple HDMI to DVI apdapter into a  LG Flatron IPS225 LED

  • A135-S4527 - DVD Drive won't read CDs but works with DVDs

    My Toshiba Satellite A135-S4527 is running Windows Vista Home Premium with SP1. It has a MAT**bleep**A DVD-RAM UJ-850S ATA Device DVD/CD-ROM drive (from System Information). It will not read CDs in the drive anymore. It doesn't give an error or anyth

  • Apple mobile device failed to start during installing itunes

    I got an error message while trying to install iTunes says that apple mobile device failed to start. i ignored this message and continued the installation process but it gave me another error and iTunes didn't work. i uninstalled it many times and tr

  • Counting number of rows in a given ResultSet

    hi, suppose i have following code : ResultSet rs = stmt.executeQuery("Select EmailAddress FROM Customer"); & i wanna know how many number of rows are there in this ResultSet .... how can i do that... is there any method i can use ... thanx in advance