Clean-up code - Close Database Connection

I have a Stateless Session Bean that implements a Web Service. This bean opens a database connection. I need to close it before the application is undeployed or the Application Server (Glassfish) is restarted, etc. I have tried shutdown hooks, predestroy and preremove annotations but none of it works.
In a few words, I want to release resources when they are not needed, but not before that.
I have used Google in every way I can imagine but I haven't turned up with anything.
Any ideas?

Duffy, I appreciate your reponse on this issue. But what is the difference, seeing that a stateless bean is response-oriented afterwhich it is returned to the pool. Not sure I know what you mean here.
A pool of connections is not the same as a pool of stateless session beans. And I don't think that returning an instance of one to its pool necessarily means that the other is automagically cleaned up as well.
I will admit now that I'm not an EJB expert.
It almost seemed to me that you were saying you'd recommend making the size of the connection and SLSB pools identical. You'd dedicate one connection to each SLSB, marrying the two together for as long as ye both shall live.
I think the design will make acquiring a connection littered all over code body. If the connection will be reused in at least 2 method it is better to create the connection in the postConstruct annotated method and remember after the bean services the client request, it is in itself placed in a pool. So nothing is lost.Maybe you're right. I'm not much with EJBs. I use Spring exclusively.
%

Similar Messages

  • 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

  • How to close database connections in Crystal Reports

    I am using the following code to connect to database. I can either pass JNDIName or I can provide values for others by leaving JNDI name empty.
    If i use JNDI name, it will use a connection from the connection pool of App Server (in my case Weblogic), but it is not releasing the connection after use. Connection remains even if I logoff from the application. If i keep my max connections as 15 in weblogic, after clicking the page with crystal report 15 times all will remain active and users will not be able to login to the application.
    If i use connectionString and others without using JNDI Name, it directly connects to database. So it creates a connection in database server directly without using connection pool of weblogic. If i check weblogic, it shows no connection in use as expected, but if i check database, i can see the no. of connections increasing everytime a user clicks a crystal report page.
    When the connection touches the maximum allowed connection in server, every application using the same server goes down
    How can I close the connection which was created for the viewing the report?
    String reportName = "/reports/BankBalance.rpt";
    ReportClientDocument clientDoc = (ReportClientDocument) session.getAttribute(reportName);
    if (clientDoc == null)
             clientDoc = new ReportClientDocument();
             clientDoc.setReportAppServer(ReportClientDocument.inprocConnectionString);
            // Open report
            clientDoc.open(reportName, OpenReportOptions._openAsReadOnly);
           String connectString = ""; // jdbc:sybase:Tds:DBSERVERNAME:9812/DBNAME?ServiceName=DBNAME
           String driverName = "";    // com.sybase.jdbc3.jdbc.SybDriver
           String JNDIName = "DS_APP";
           String userName = "";
           String password = "";
           // Switch all tables on the main report and sub reports
           CRJavaHelper.changeDataSource(clientDoc, userName, password, connectString, driverName, JNDIName);
         // logon to database
          CRJavaHelper.logonDataSource(clientDoc, userName, password);
    // Store the report document in session
    session.setAttribute(reportName, clientDoc);
                   // Create the CrystalReportViewer object
                          CrystalReportViewer crystalReportPageViewer = new CrystalReportViewer();
         String reportSourceSessionKey = reportName+"ReportSource";
         Object reportSource = session.getAttribute(reportSourceSessionKey);
         if (reportSource == null)
              reportSource = clientDoc.getReportSource();
              session.setAttribute(reportSourceSessionKey, reportSource);
         //     set the reportsource property of the viewer
         crystalReportPageViewer.setReportSource(reportSource);
         crystalReportPageViewer.setHasRefreshButton(true);
         crystalReportPageViewer.setToolPanelViewType(CrToolPanelViewTypeEnum.none);
         // Process the report
         crystalReportPageViewer.processHttpRequest(request, response, application, null);

    the sample shows how to clear RAS and Enterprise resources after viewing report.
    1. If you use unmanaged RAS - as I can see you using setReportAppServer, then remove the enterprise related stuff : instantiating and cleaning code.
    The sample code is meant to give you an idea on how you can release the resources after done with viewing report. In your case all you need to do for cleaning is call close() on ReportDocumentObject. The sample will need to be modified for your requirements.

  • How to close database connections

    I am using the following code to connect to database. I can either pass JNDIName or I can provide values for others by leaving JNDI name empty.
    If i use JNDI name, it will use a connection from the connection pool of App Server (in my case Weblogic), but it is not releasing the connection after use. Connection remains even if I logoff from the application
    String reportName = "/reports/BankBalance.rpt";
    ReportClientDocument clientDoc = (ReportClientDocument) session.getAttribute(reportName);
    if (clientDoc == null)
    clientDoc = new ReportClientDocument();
                   clientDoc.setReportAppServer(ReportClientDocument.inprocConnectionString);
    // Store the report document in session
    session.setAttribute(reportName, clientDoc);
    String connectString = ""; // jdbc:sybase:Tds:DBSERVERNAME:9812/DBNAME?ServiceName=DBNAME
    String driverName = "";    // com.sybase.jdbc3.jdbc.SybDriver
    String JNDIName = "DS_APP";
    String userName = "";
    String password = "";
    CRJavaHelper.changeDataSource(clientDoc, userName, password, connectString, driverName, JNDIName);
    CRJavaHelper.logonDataSource(clientDoc, userName, password);
    // Store the report document in session
    session.setAttribute(reportName, clientDoc);
    // Process the report
    crystalReportPageViewer.processHttpRequest(request, response, application, null);

    the sample shows how to clear RAS and Enterprise resources after viewing report.
    1. If you use unmanaged RAS - as I can see you using setReportAppServer, then remove the enterprise related stuff : instantiating and cleaning code.
    The sample code is meant to give you an idea on how you can release the resources after done with viewing report. In your case all you need to do for cleaning is call close() on ReportDocumentObject. The sample will need to be modified for your requirements.

  • Open and close database connection jsp page

    hi there, i wanna know about how to open database connection to Mysql at the beginning of the page and close the connection at the end of the page. The jsp page contain all processing code.
    plz help me...thx thx

    <html>
    <head>
    <basefont face="Arial">
    </head>
    <body>
    <%@ page language="java" import="java.sql.*" %>
    <%!
    // define variables
    String id;
    String firstName;
    String lastName;
    // define database parameters, change this according to your needs
    String host="localhost";
    String user="root";
    String pass="";
    String db="test";
    String conn;
    %>
    <table border="1" cellspacing="1" cellpadding="5">
    <tr>
    <td><b>id</b></td>
    <td><b>first name</b></td>
    <td><b>last name</b></td>
    </tr>
    <%
    Class.forName("org.gjt.mm.mysql.Driver");
    // create connection string
    conn = "jdbc:mysql://" + host + "/" + db + "?user=" + user 
    + "&password=" + pass;
    // pass database parameters to JDBC driver
    Connection Conn = DriverManager.getConnection(conn);
    // query statement
    Statement SQLStatement = Conn.createStatement();
    // generate query
    // change this query according to your needs
    String Query = "SELECT id, firstname, lastname FROM abook";
    // get result
    ResultSet SQLResult = SQLStatement.executeQuery(Query);
    while(SQLResult.next())
       id = SQLResult.getString("id");
       firstName = SQLResult.getString("firstname");
       lastName = SQLResult.getString("lastname");
            out.println("<tr><td>" + id + "</td><td>" + 
         firstName + "</td><td>" + lastName + "</td></tr>");
    // close connection
    SQLResult.close();
    SQLStatement.close();
    Conn.close();
    %>
    </table>
    </body>
    </html>hi :-)
    i've got that on the net as part of the tutorial on jsp (long long time ago)
    you just have to be resourceful in finding solutions :-)
    try google :-) there are lot's of tutorial available in there ;-)
    goodluck ;-)
    regards,

  • 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

  • Opening multiple reports in Crystal Reports for VS causes database connect limit to be reached.  Seems to be no way to force Crystal Reports to close database connection (other than exiting application)

    I am working on upgrading an application that has been in use for many years.  The application is written in VB6 and I have been tasked with upgrading the current application to Crystal Reports for Visual Studio.  I am using Crystal Reports for VS Version 13.0.12.1494.  The system's database is a Sybase SQL Anywhere 16 database with an ODBC connection using integrated login.  Each of the reports has the database connection set up from within the report.  There is only once database server, so each of the reports are pointing to the same DB.  The database server is currently installed as a "Personal Server" with a limit of 10 connections. 
    I have implemented the CR viewer as part of a COM-callable wrapper that exposes a COM interface for VB6 to interact with.  Inside of my viewer component is a Winform that embeds the Crystal's Report viewer.  The COM interface basically maps the basic Crystal apis to methods that the VB6 can call (i.e., Load Report, Set Field Text, Update SQL Query, etc).  This architecture is working as designed and the reports are displaying correctly and responding correctly to changes in queries, etc.
    The issue is that after I open 9 reports, the tenth one will respond with an error indicating that the database connection limit has been reached.  The database connections used by the reports aren't released until after the application is closed.  The application is designed for a secure environment that prohibits the non-administrative user from accessing the systems desktop, so asking the user tor restart the application after 10 reports isn't a viable option.
    I have checked and database connection pooling is turned off for the SQL Anywhere 16 driver.
    I have been digging on this for a few days and have tried adding code in the FormClosed event to close and dispose of the Report Document as follows:
    ReportDocument reportDoc= (ReportDocument) crystalReportViewer1.ReportSource;
    reportDoc.Close();
    reportDoc.Dispose();
    GC.Collect();       // Force garbage collection on disposed items
    I have also tried the following (as well as maybe 20 or so other permutations) trying to fix the issue with no success.  
    ReportDocument reportDoc= (ReportDocument) crystalReportViewer1.ReportSource;
    foreach (Table table in reportDoc.Database.Tables)
         table.Dispose();
    crystalReportViewer1.ReportSource = null;
    reportDoc.Database.Dispose();
    reportDoc.Close();
    reportDoc.Dispose();
    reportDoc = (ReportDocument)crystalReportViewer1.ReportSource;
    GC.Collect();       // Force garabe collection on disposed items
    Any ideas or suggestions would be greatly appreciated.  I have been pulling my hair out on this one!

    Hi Ludek,
    Thanks so much for the quick reply.  Unfortunately I did not have time to work on the reporting project Friday afternoon, but did a quick test this morning with some interesting results.  I'm hoping if I describe what I'm doing, you can show me the error of my ways.  This is really my first major undertaking with Crystal Reports.
    If I simply load the report, then close and dispose, I don't hit the limit of 10 files.  Note that I do not logon manually in my code as the logon parameters are all defined within the reports themselves.  The logon happens when you actually view the report.  Loading the report doesn't seem to actually log in to the DB.
    What I did was create a very simple form with a single button that creates the WinForm class which contains the Crystal Viewer.  It then loads the report, sets the ReportSource property on the CrystalReportsViewer object contained in the WInForm and shows the report. The report does show correctly, until the 10 reports limit is reached.
    The relevant code is shown below. More than I wanted to post, but i want to be as complete and unambiguous as possible. 
    This code displays the same behavior as my earlier post (after 10 reports we are unable to create another connection to the DB).
    // Initial Form that simply has a button
      public partial class SlectReport : form
            public SelectReport()
                InitializeComponent();
            private void button1_Click(object sender, EventArgs e)
                ReportDocument rd = new ReportDocument();
                ReportForm report = new ReportForm();
                try
                    rd.Load(@"Test.rpt");
                    report.ReportSource = rd;
                    report.Show();
             catch (Exception ex)
                  MessageBox.Show(ex.Message);
    // The WinForm containing the Crystal Reports Viewer
        public partial class ReportForm : Form
            public ReportForm()
                InitializeComponent();
            private void Form1_Load(object sender, EventArgs e)
                this.crystalReportViewer1.RefreshReport();
                this.FormClosed += new FormClosedEventHandler(ReportForm_FormClosed);
            void ReportForm_FormClosed(object sender, FormClosedEventArgs e)
                ReportDocument rd;
                rd = (ReportDocument)crystalReportViewer1.ReportSource;
                rd.Close();
                rd.Dispose();
            public object ReportSource
                set { crystalReportViewer1.ReportSource = value; }
    Again, any guidance would be greatly appreciated. 

  • How I can close Database connection?

    I am using the following to open Database connections in Java class.
    Class.forName("oracle.jdbc.driver.OracleDriver");
    con = DriverManager.getConnection("URL","user","password");
    But I do not know how I can have it closed.
    This cause an SQL error: Maximum open cursors exceeded.

    Thanks so much. Your explanation is so clear.
    Here is the whole code. Thanks for your help.
    package xxx.xx.xxx;
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    public class Format_BaseTable {
    Connection con = null;
    Statement stmt = null;
    Statement stmt1 = null;
    ResultSet rs = null;
    ResultSet rs1 = null;
    PreparedStatement ps = null;
    PreparedStatement ps1 = null;
    public Format_BaseTable() {}
    public static String valueOf(String oldStr)
    StringTokenizer st = new StringTokenizer(oldStr.trim(), "-");
    char zero = '0';
    String dem_zero = ".0";
    String newStr = "";
    while(st.hasMoreTokens()) {
    String degree = st.nextToken();
    String minute = st.nextToken();
    String second = st.nextToken();     
    if (minute.length() == 1) {
    minute = zero + minute;
    if (second.length() == 1) {
    second = zero + second;
    if (second.length() == 2) {
    second = second + dem_zero;
    if (second.length() == 3) {
    second = zero + second;
    if (second.length() == 5) {
    double d = Double.parseDouble(second);
    second = String.valueOf(Math.round(d));
    newStr = degree + " " + minute + " " + second;
    return newStr;
    public static double feetToMeter(int ft)
    double mt = ft * 0.305;
    return mt;
    public void doConvert() { 
    try {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    con = DriverManager.getConnection("url","user","password");
    stmt = con.createStatement();
    stmt1 = con.createStatement();
    rs = stmt.executeQuery("SELECT cla_seqnum, str_leased, nad27_lat, nad27_lon, nad83_lat, nad83_lon, ge_ft, sh_ft, osh_ft, ov_faa_approv_ft, ant_tip_ft, ant_ctr_line_ft FROM cl_antenna_base WHERE application_user_id = 'SQL LOADER'");
    rs1 = stmt1.executeQuery("SELECT mwa_seqnum, nad27_lat, nad27_lon, nad83_lat, nad83_lon, ge_ft, osh_ft, cl_ft FROM mw_antenna_base WHERE application_user_id = 'SQL LOADER'");
    int cl_seqnum = 0;
    String leased = "";
    String ownership = "";
    String str_code = "";
    String cl_nad27_lat = "";
    String cl_nad27_lon = "";
    String cl_nad83_lat = "";
    String cl_nad83_lon = "";
    int cl_ge_ft = 0;
    int cl_ge_mt = 0;
    int cl_sh_ft = 0;
    int cl_sh_mt = 0;
    int cl_osh_ft = 0;
    int cl_osh_mt = 0;
    int cl_ov_faa_approv_ft = 0;
    int cl_ov_faa_approv_mt = 0;
    int cl_ant_tip_ft = 0;
    int cl_ant_tip_mt = 0;
    int cl_ant_ctr_line_ft = 0;
    int cl_ant_ctr_line_mt = 0;
    int i = 1;
    int mw_seqnum = 0;
    String mw_nad27_lat = "";
    String mw_nad27_lon = "";
    String mw_nad83_lat = "";
    String mw_nad83_lon = "";
    int mw_ge_ft = 0;
    int mw_ge_mt = 0;
    int mw_osh_ft = 0;
    int mw_osh_mt = 0;
    int mw_cl_ft = 0;
    int mw_cl_mt = 0;
    int j = 1;
    while(rs.next())                    // For Cellular/PCS
    System.out.println("\n\nCellular/PCS Record #" + i);
    cl_seqnum = rs.getInt("cla_seqnum");
    System.out.println("cla_seqnum =" + cl_seqnum);
    if (rs.getString("str_leased") != null) {
    leased = rs.getString("str_leased");
    } else {
    leased = "";
         StringTokenizer st = new StringTokenizer(leased, "/");
    while(st.hasMoreTokens()) {
         ownership = st.nextToken();
         str_code = st.nextToken();
    if (rs.getString("nad27_lat") != null) {
    cl_nad27_lat = valueOf(rs.getString("nad27_lat"));
    } else {
    cl_nad27_lat = "";
         System.out.println("cl_nad27_lat = " + cl_nad27_lat);
    if (rs.getString("nad27_lon") != null) {
    cl_nad27_lon = valueOf(rs.getString("nad27_lon"));
    } else {
    cl_nad27_lon = "";
    System.out.println("cl_nad27_lon = " + cl_nad27_lon);
    if (rs.getString("nad83_lat") != null) {
    cl_nad83_lat = valueOf(rs.getString("nad83_lat"));
    } else {
    cl_nad83_lat = "";
    System.out.println("cl_nad83_lat = " + cl_nad83_lat);
    if (rs.getString("nad83_lon") != null) {
    cl_nad83_lon = valueOf(rs.getString("nad83_lon"));
    } else {
    cl_nad83_lon = "";
    System.out.println("cl_nad83_lon = " + cl_nad83_lon);
    cl_ge_mt = (int)feetToMeter(rs.getInt("ge_ft"));
    System.out.println("&&&&&&&&&&&&&&&&&&&cl_ge_mt = " + cl_ge_mt);
    cl_sh_mt = (int)feetToMeter(rs.getInt("sh_ft"));
    System.out.println("&&&&&&&&&&&&&&&&&&&cl_sh_mt = " + cl_sh_mt);
    cl_osh_mt = (int)feetToMeter(rs.getInt("osh_ft"));
    System.out.println("&&&&&&&&&&&&&&&&&&&cl_osh_mt = " + cl_osh_mt);
    cl_ov_faa_approv_mt = (int)feetToMeter(rs.getInt("ov_faa_approv_ft"));
    System.out.println("&&&&&&&&&&&&&&&&&&&cl_ov_faa_approv_mt = " + cl_ov_faa_approv_mt);
    cl_ant_tip_mt = (int)feetToMeter(rs.getInt("ant_tip_ft"));
    System.out.println("&&&&&&&&&&&&&&&&&&&cl_ant_tip_mt = " + cl_ant_tip_mt);
    cl_ant_ctr_line_mt = (int)feetToMeter(rs.getInt("ant_ctr_line_ft"));
    System.out.println("&&&&&&&&&&&&&&&&&&&cl_ant_ctr_line_mt = " + cl_ant_ctr_line_mt);
         // update NAD27 and NAD83 data in CL_ANTENNA table
    ps = con.prepareStatement("UPDATE cl_antenna_base SET str_leased = ?, structure_code = ?, nad27_lat = ?, nad27_lon =?, nad83_lat = ?, nad83_lon = ?, ge_mt = ?, sh_mt = ?, osh_mt = ?, ov_faa_approv_mt = ?, ant_tip_mt = ?, ant_ctr_line_mt = ? WHERE cla_seqnum = " + cl_seqnum);
    ps.setString(1, ownership);
    ps.setString(2, str_code);
    ps.setString(3, cl_nad27_lat);
    ps.setString(4, cl_nad27_lon);
    ps.setString(5, cl_nad83_lat);
    ps.setString(6, cl_nad83_lon);
    ps.setInt(7, cl_ge_mt);
    ps.setInt(8, cl_sh_mt);
    ps.setInt(9, cl_osh_mt);
    ps.setInt(10, cl_ov_faa_approv_mt);
    ps.setInt(11, cl_ant_tip_mt);
    ps.setInt(12, cl_ant_ctr_line_mt);
         ps.executeUpdate();          
         i++;
    } // end of while
    while(rs1.next())                    // For Microwave
    System.out.println("\n\nMicrowave Record #" + j);
    mw_seqnum = rs1.getInt("mwa_seqnum");
    System.out.println("mw_seqnum =" + mw_seqnum);
    if (rs1.getString("nad27_lat") != null) {
    mw_nad27_lat = valueOf(rs1.getString("nad27_lat"));
    } else {
    mw_nad27_lat = "";
    System.out.println("mw_nad27_lat = " + mw_nad27_lat);
    if (rs1.getString("nad27_lon") != null) {
    mw_nad27_lon = valueOf(rs1.getString("nad27_lon"));
    } else {
    mw_nad27_lon = "";
    System.out.println("mw_nad27_lon = " + mw_nad27_lon);
    if (rs1.getString("nad83_lat") != null) {
    mw_nad83_lat = valueOf(rs1.getString("nad83_lat"));
    } else {
    mw_nad83_lat = "";
    System.out.println("mw_nad83_lat = " + mw_nad83_lat);
    if (rs1.getString("nad83_lon") != null) {
    mw_nad83_lon = valueOf(rs1.getString("nad83_lon"));
    } else {
    mw_nad83_lon = "";
    System.out.println("mw_nad83_lon = " + mw_nad83_lon);
    mw_ge_mt = (int)feetToMeter(rs1.getInt("ge_ft"));
    System.out.println("&&&&&&&&&&&&&&&&&&&mw_ge_mt = " + mw_ge_mt);
    mw_osh_mt = (int)feetToMeter(rs1.getInt("osh_ft"));
    System.out.println("&&&&&&&&&&&&&&&&&&&mw_osh_mt = " + mw_osh_mt);
    mw_cl_mt = (int)feetToMeter(rs1.getInt("cl_ft"));
    System.out.println("&&&&&&&&&&&&&&&&&&&mw_cl_mt = " + mw_cl_mt);
    // update NAD27 and NAD83 data in MW_ANTENNA table
    ps1 = con.prepareStatement("UPDATE mw_antenna_base SET nad27_lat = ?, nad27_lon =?, nad83_lat = ?, nad83_lon = ?, ge_mt = ?, osh_mt = ?, cl_mt = ? WHERE mwa_seqnum = " + mw_seqnum);
    ps1.setString(1, mw_nad27_lat);
    ps1.setString(2, mw_nad27_lon);
    ps1.setString(3, mw_nad83_lat);
    ps1.setString(4, mw_nad83_lon);
    ps1.setInt(5, mw_ge_mt);
    ps1.setInt(6, mw_osh_mt);
    ps1.setInt(7, mw_cl_mt);
    ps1.executeUpdate();
    j++;
    } // end of while
    } catch(SQLException se) {
         System.out.println("SQL Exc" + se.getMessage());
    se.printStackTrace();
    } catch(Exception e) {
    System.out.println(" Exc" + e.getMessage());
    e.printStackTrace();
    finally
              try
                   rs.close();
                   stmt.close();
                   dbConn.freeConnection("system", conn);
                   conn.close();
              } catch (SQLException e)
    } // end of doConvert
    public static void main(String args[]) {
    Format_BaseTable old_nad = new Format_BaseTable();
    old_nad.doConvert();
    } // end of class

  • Close database connections

    I developed a small application which talks to Oracle database to do sevreral transactions. I am using a connection pool class in my main program. I used to several methods in my class to do database transactions. When ever I close connection at the end of my each method in finally block it says connection closed when I run my program for the second time. First time it doesn't say anything and runs well. So I removed finally block in each method then it works fine.
    Question: I was wondering how my program works without closing connections in each method. Does ConnectionPool will take care of connections even if I don't close connection?
    Please let me know.
    Thanks.

    Thank You. My connection pool has destroy() method
    which will close the connection. I think when my main
    class is out of scope the connection pool is taking
    care of closing the connection. If you are not calling a method then the only way that can happen is via the garbage collector.
    And relying on the garbage collector in java to clean up resources is a really, really bad idea.

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

  • How to correct close database connection after report generation

    Hello
    I have problem a with alive database connection after report creation and report  closing. How to properly to close connection to database?
    Best regards
    Edited by: punkers84 on Jun 17, 2011 10:38 AM

    that's what I am doing... after viewing the report, I call the close method on the window closing event of the container window. but the connection is still open. I had a lot of other issues with my jdbc driver but after downgrading to an older version those issues are resolved.Only this one is still there! Is there any other way to close the connection (like using dbcontroller or etc.)?

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

  • When to close database connection

    I'm working on an application that reads a customer number from an Access database and returns the name, address, etc of the customer number.
    My question is the following, is it best practice to close the database each time the request has been processed, and open it every time a request is made?

    Hai
    If u r sure that the application is a single user, then go for the singleton pattern. In that case u will be creating a single instance of the java.sql.Connection class. Before doing any DB operation check whether the connection is null or not, if its null create a new connection.
    If the application is a multi user one, go for connection pooling.
    Close the DB connection before exiting the application.

  • Servlet close Database connection

    Hi,
    I have a problem with my servlet. When I call the Servlet from the applet the servlet's init() is call. In the init() I also open a connection to database. By this two things are no problems. But when I later want call selectAllCdsQuery() of the servlet with RMI I get a NullPointerException for the connection dbconn. Why?
    // Applet Source
    private void initComponents() {
    try {
    URL url = new URL "http://192.168.0.2:8080/examples/servlet/cd_shop_servlet");
    url.openStream(); //Call the Servlet
    } catch (Exception e) {
    System.out.println("Fehler");
    // Servlet Source
    public PreparedStatement selectAllCdsQuery() throws RemoteException {
    try {
    sql_statement = dbconn.prepareStatement("SELECT * ..."); // here I get a NullPointer Exception
    } catch (Exception e) {
    System.out.println("Fehler bei selectAllCdsQuery Prepare");
    System.out.println(e.toString());
    return sql_statement;
    public void init(ServletConfig config) throws ServletException {
    super.init(config);
    System.setSecurityManager(new RMISecurityManager());
    try {
    DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());     
    Properties p = new Properties();
    p.put("***","***");
    p.put("autoReconnect", "true");
    dbconn = DriverManager.getConnection("jdbc:odbc:SQL_Server",p );
    cd_shop_servlet obj = new cd_shop_servlet();
    Naming.rebind("//192.168.0.2/cd_shop", obj);
    System.out.println("CD Shop bound in registry");     
    } catch (Exception e) {
    System.out.println("CD Shop err: " + e.getMessage());
    e.printStackTrace();

    Are you sure that the init method is being called? I ask because this isn't really being used as a servlet. It's being invoked through RMI, not directly through an HttpRequest so it's quite possible that it's not being loaded like a servlet.

  • Database connection to MS SQL 2005 (URGENT Help Needed)

    Hi all,
    Does anyone know how to connect my adobe form to MS SQL 2005?
    I have this code:
    try {
         InitialContext initialContext = new InitialContext ();
         DataSource dataSource = (DataSource) initialContext.lookup ("jdbc/MyAlias");
          java.sql.Connection connection = dataSource.getConnection ();
    } catch (SQLException e) {
         // handle exception
    } catch (NamingException e) {
    // handle exception
    Other than these, what else do i need to do inorder to get my database connection up?
    And after my database connection is up, how do i test to check if my database connection is up or not?
    How do i extract the information from the database and put them onto the textfields/dropdownlists on my form?
    Thanks In Advance

    Hi Mel,
    After implementing the codes and modifying them, some of them are underlined, why is this so? =X
    Or are u willing to exchange msn so i could send u the screenshot instead?
    Thanks In Advance
    (Sorry im not that good in this)
    (I shall underline the areas which represents the red underline in my web dynpro)
         //Code for database connection.
           InitialContext ctx = new InitialContext();
           DataSource ds = (DataSource)_ctx.lookup("jdbc/JXDataSource");_
           Connection conn = ds.getConnection();
           Statement st = null;
           ResultSet rs = null;
           IPrivateDetailed_Claims_FormView.IFillDataElement dataEle = null;
           st = conn.createStatement();
         //     Execute the appropriate SQL query
           rs = st.executeQuery("SELECT NAME WHERE VENDORCODE='9000116L' ");_     
           while (rs.next())       {
         //     Code that will populate your VN based on the data obtained in the ResultSet.
           dataEle = wdContext.createFillDataElement();
           dataEle.setName(_rs.getString(1)_);
          // dataEle.setAge(rs.getInt(2));
          // dataEle.setAddress(rs.getString(3));
           //wdContext.nodeFillData.addElement(dataEle);
           //  Close the connections
           rs.close();
           st.close();
                      conn.close();
    Edited by: JingXuan Lim on Jan 25, 2008 4:59 AM
    Edited by: JingXuan Lim on Jan 25, 2008 5:00 AM

Maybe you are looking for

  • Apple TV (1st gen) will not connect to iTunes

    I am at wit's end. Until a couple of days ago, my 1st gen Apple TV connected fine to iTunes. Now, it will not connect no matter what. I have tried the following: 1) restart both ATV and my machine (Win 7 running iTunes 10.7) 2) restored ATV factory s

  • Problem in factory method, how to pass arguments ?

    Hello it's me again :) here's the code : package print; import java.util.*; import static print.Print.*; interface Fact<T> { T create(String n);; T create (); class PetColl {       public String toString() {       return getClass().getSimpleName();  

  • Adobe Camera Raw Interface - Can anyone help?

    I have Photoshop Elements 9 installed on my PC running under XP. I have version 6.5 of Camera Raw installed. My camera is a Nikon D60 which records its Raw images as .NEF. When I open a Raw file in PSE9 the Camera Raw Interface does NOT open. When I

  • PC as a bluetooth Device and accept input from other devices

    I need to set my PC up as a bluetooth device by use of a bluetooth dongle connected to my PC. I need to have a program running on my PC that will detect other bluetooth devices and connect with them, accept input from them. Please help me do this. an

  • Setting EX2007 mailbox permissions with Exchange Management Shell not reflected in Exchange Management Console

    Hello, I'm trying to use PowerShell to script some mailbox permissions.  The mailbox permissions I set in the shell are not displaying in the EMC.  The command I'm using is: add-MailboxPermission -accessrights fullaccess -identity $username -user MYD