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

Similar Messages

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

  • How to manage database connections

    Hi, I have been trying to find the best way of doing database connections, My application will not be used by many users since its an intranet application used by administrators only to change settings.
    I want to be able to connect to db from a servlet but not have to make the connection all the time, I was thinking of creating my own ContinuousConnection class which basically keeps the connection and all you do is getConnection which checks if the connection is "up" or not, if it is up then just give it as the return value else, just create a new connection since the driver class has already been loaded...if it is null then just load the driver and make the connection.
    this way in differenet functions that i have in the servlet dont have to make connections all the time.
    Is there a better way of doing this?
    I was thinking of putting the connection object in the data section of the servlet, but then it is more or less like static data amongst all threads created to run the servlet and I dont know what would happen if 2 querries are run from the same connection by different serving threads...can someone please explain me this..
    I know a good way of managing connections is using a pool..but i dont know how useful is that here...also i am not very familiar with a pool..can someone please explain me the idea behind it..and how it works...that would be just perfect.
    Thank you very much.
    Ankur

    IIRC to setup tomcat connection pooling when using an Oracle database (for example):
    Add something like this to the server.xml file:
            <Context path="/myProject" docBase="myProject" debug="0"
                     reloadable="true" crossContext="true">                
                    <Resource name="jdbc/ORAC" auth="Container" type="javax.sql.DataSource"/>
              <ResourceParams name="jdbc/ORAC">
                <parameter>
                  <name>factory</name>
                  <value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
                </parameter>
                <parameter>
                  <name>driverClassName</name>
                  <value>oracle.jdbc.driver.OracleDriver</value>
                  </parameter>
                <parameter>
                  <name>url</name>
                  <value>jdbc:oracle:thin:@xxx.xxx.xxx.xxx:1521:XXXX</value>
                </parameter>
                <parameter>
                  <name>username</name>
                  <value>xxxxx</value>
                </parameter>
                <parameter>
                  <name>password</name>
                  <value>xxxxx</value>
                </parameter>
                <parameter>
                  <name>removeAbandoned</name>
                  <value>true</value>
                </parameter>
                <parameter>
                  <name>logAbandoned</name>
                  <value>true</value>
                </parameter>
                <parameter>
                  <name>maxActive</name>
                  <value>20</value>
                </parameter>
                <parameter>
                  <name>maxIdle</name>
                  <value>10</value>
                </parameter>
                <parameter>
                  <name>maxWait</name>
                  <value>-1</value>
                </parameter>
              </ResourceParams>                       
            </Context>  This needs to go in between the <Host> ... </Host> tags (probably at the bottom) in the server.xml file (${CATALINA_HOME}/conf). You must put this in the correct place in the xml file or you'll get errors.
    Then you need to add this to your web.xml file:
        <resource-ref>
             <description>Oracle Datasource</description>
             <res-ref-name>jdbc/ORAC</res-ref-name>
         <res-type>javax.sql.DataSource</res-type>
         <res-auth>Container</res-auth>
        </resource-ref>Again this needs to go in the correct place (as per the dtd)
    Then to get a connection:
    final Context initContext = new InitialContext();               
    final DataSource ds = (DataSource) initContext.lookup("java:/comp/env/jdbc/ORAC");                              
    final Connection conn = ds.getConnection();You probably want to wrap getting these connections in a class (i.e. with a getConnection method). And remember to close the connections when you've finished with them.

  • How to get database connection in applet

    Hi,
    I am trying to prepare database connection in applet. After preparing connection with database it'll read same values from table.
    At the time of development it works fine. I have used esclipse IDE for coding and testing.
    But when I try to call that applet from browser. It is giving ClassNotFound exception.
    Does anybody know How to get database connection in applet ?
    Please help me if anybody know solution for this.
    Thanks,
    Rajesh

    As per my knowledge is conserned
    1 u can get the database connection in a jsp page and u send the result set as param to the applet and u can use retrieved values as if they were of the same applet if u r interested i can send the db connetion coding for jsp my id [email protected]

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

  • I have read that new purchases of macbook pro will get free upgrade to LION OS. When and how do I go about this?

    I have read that new purchases of macbook pro will get free upgrade to LION OS. When and how do I go about this?

    http://www.apple.com/pr/library/2011/06/06lion.html
    The Mac OS X Lion Up-To-Date upgrade is available at no additional charge via the Mac App Store to all customers who purchased a qualifying new Mac system from Apple or an Apple Authorized Reseller on or after June 6, 2011. Users must request their Up-To-Date upgrade within 30 days of purchase of their Mac computer. Customers who purchase a qualifying Mac between June 6, 2011 and the date when Lion is available in the Mac App Store will have 30 days from Lion’s official release date to make a request.
    Currently that's the only information available. I suspect more will be posted as we get closer to launch.

  • How to access  database connection from datatsource in a standalone java ap

    My java standalone application wants connection to database with lookup to datasource name which is configured in the oc4j app server.
    Please guide me with some ideas to acheieve this.

    user510497,
    Following sample program requires access to classes in "oc4j.jar" file.
    Test environment:
    * Server:
    + OC4J stand-alone 10.1.2.0.2
    + Red Hat Enterprise Linux AS release 3
    + Java HotSpot(TM) Client VM (build 1.4.2_08-b03, mixed mode)
    + Oracle Database 10g Release 10.1.0.4.0 - 64bit Production
    * Client
    + Microsoft Windows XP Professional Version 2002 Service Pack 2
    + Java HotSpot(TM) Client VM (build 1.5.0_08-b03, mixed mode, sharing)
    import java.sql.Connection;
    import java.sql.DatabaseMetaData;
    import java.sql.SQLException;
    import java.util.Properties;
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import javax.sql.DataSource;
    public class DataSrc2 {
      public static void main(String[] args) {
        Connection conn = null;
        Properties l_props = new Properties();
        l_props.put(Context.INITIAL_CONTEXT_FACTORY,
                    "com.evermind.server.rmi.RMIInitialContextFactory");
        l_props.put(Context.PROVIDER_URL, "ormi://your_OC4J_host/");
        l_props.put(Context.SECURITY_PRINCIPAL, "your_OC4J_user");
        l_props.put(Context.SECURITY_CREDENTIALS, "your_OC4J_password");
        Context l_jndiContext = null;
        try {
          l_jndiContext = new InitialContext(l_props);
          Object l_obj = l_jndiContext.lookup("default-data-source");
          DataSource ds = (DataSource) l_obj;
          conn = ds.getConnection("scott","tiger");
          DatabaseMetaData dbmd = conn.getMetaData();
          System.out.println(dbmd.getDatabaseProductVersion());
        catch (NamingException x_naming) {
          x_naming.printStackTrace();
        catch (SQLException xSql) {
          xSql.printStackTrace();
        finally {
          if (l_jndiContext != null) {
            try {
              l_jndiContext.close();
            catch (NamingException x_naming) {
              System.err.println("Failed to close JNDI context.");
              x_naming.printStackTrace();
          if (conn != null) {
            try {
              conn.close();
            catch (SQLException xSql) {
              System.err.println("Failed to close [database] connection.");
              xSql.printStackTrace();
    }NOTES:
    1. Datasource lookup name is value of "default-data-source" attribute of "orion-application" element in file:
    <OC4J_HOME>/j2ee/home/config/application.xmlGood Luck,
    Avi.

  • What is correlation ? when and how to use it in BPEL process?

    Hi,
    What is correlation ? when and how to use it in BPEL process?
    Thanks

    Hi:
    Take a look at this entry http://blog.andrade.inf.br/2010/03/oracle-bpel-11g-correlation-sets.html
    thx
    best

  • How to establish a MYSQL Database connection in JSP page.

    Hi People,
    Tell me how to establish mysql database connection in JSP page.
    Needed details on:
    1) what are all the mysql drivers need to be included.
    2) what is the syntax for establish a database connection

    hi,
    http://tomcat.apache.org/tomcat-5.5-doc/jndi-datasource-examples-howto.htmlsee down for mysql config with tomcat

  • [svn:fx-trunk] 10545: Make DataGrid smarter about when and how to calculate the modulefactory for its renderers when using embedded fonts

    Revision: 10545
    Author:   [email protected]
    Date:     2009-09-23 13:33:21 -0700 (Wed, 23 Sep 2009)
    Log Message:
    Make DataGrid smarter about when and how to calculate the modulefactory for its renderers when using embedded fonts
    QE Notes: 2 Mustella tests fail:
    components/DataGrid/DataGrid_HaloSkin/Properties/datagrid_properties_columns_halo datagrid_properties_columns_increase0to1_halo
    components/DataGrid/DataGrid_SparkSkin/Properties/datagrid_properties_columns datagrid_properties_columns_increase0to1
    These fixes get us to measure the embedded fonts correctly when going from 0 columns to a set of columns so rowHeight will be different (and better) in those scenarios
    Doc Notes: None
    Bugs: SDK-15241
    Reviewer: Darrell
    API Change: No
    Is noteworthy for integration: No
    tests: checkintests mustella/browser/DataGrid
    Ticket Links:
        http://bugs.adobe.com/jira/browse/SDK-15241
    Modified Paths:
        flex/sdk/trunk/frameworks/projects/framework/src/mx/controls/DataGrid.as
        flex/sdk/trunk/frameworks/projects/framework/src/mx/controls/dataGridClasses/DataGridBase .as
        flex/sdk/trunk/frameworks/projects/framework/src/mx/controls/dataGridClasses/DataGridColu mn.as

    Hi Matthias,
    Sorry, if this reply seems like a products plug (which it is), but this is really how we solve this software engineering challenge at JKI...
    At JKI, we create VI Packages (which are basically installers for LabVIEW instrument drivers and toolkits) of our reusable code (using the package building capabilities of VIPM Professional).  We keep a VI Package Configuration file (that includes a copy of the actual packages) in each of our project folders (and check it into source code control just as we do for all our project files).  We also use VIPM Enterprise to distribute new VI Packages over the network.
    Also, as others have mentioned, we use the JKI TortoiseSVN Tool to make it easy to use TortoiseSVN directly from LabVIEW.
    Please feel free to contact JKI if you have any specific questions about these products.
    Thanks,
    -Jim 

  • Free bumper case when and how?

    Steve indicated that every iPhone 4 owner would receive a free bumper case to hopefully correct the antenna issue. When and how does one receive the case? I must admit that I have only had a few dropped calls. I live in an area that has a weak signal and my 3G had not one dropped call in 2 years!!!

    Apple will offer a free iPhone 4 Bumper or other select cases to iPhone 4 customers. Details on how to order a free Bumper or case will be available soon on apple.com, details most likely this week.

  • Problem in Oracle Database Connectivity in JSP

    I am having big problem such as Oracle Database connectivity problem
    Following code i am used for database connection. but it throw an exception call class not found exception.
    Pls any one can help me. With a sample code for Oracle Database connection in JSP
    Class.forName ("oracle.jdbc.driver.OracleDriver");
    String url="jdbc:oracle:thin:@172.25.44.54:1521:bbo";
    con = DriverManager.getConnection(url,"user", "user123");
    Thank you

    Well i've never used oracle or their drivers before but i'm presuming that you'd go to oracle.com or something and look for downloads. Otherwise you could goodle for Oracle JDBC drivers. Then just follow the instructions.
    Again i've never used JSP but if you have a manifest file somewhere you'll need to put a class-path: entry in their referecning the jar file with the driver so that it is availble at run-time.
    Wes

  • 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

Maybe you are looking for

  • Free goods in purchase order

    hi guys: I got a problem. vendors will give me few goods for free when I purchase a material at a level of quantity.now I can creat a purchase order to purchase A with few quantity of A free, and the question is how can I purchase A with B free? wait

  • Context mapping for Interactive ADOBE form

    I could able to create the form context from the web dynpro context. I am stucked at mapping between the two contexts. When I insert the element Interactive form in the layout of Web Dynpro and specify the template source, We have the option of  auto

  • Problem with shared objects synchoronization.

    I encountered a small problem with shared objects. I'm working on a program that creates chat rooms of a fixed size of 30 users. When the 31th user comes, a new room is created. The idea is that the client first connects to the first room and checks

  • Tmboot: internal error: CMDTUX_CAT:1098: ERROR: Can't create queue

    Hi, i am getting "tmboot :internal error:CMDTUX_CAT:1098 error:cant create queue" *RESOURCES IPCKEY 123456 #Example: #IPCKEY 123456 DOMAINID simpapp MASTER simple MAXACCESSERS 10 MAXSERVERS 5 MAXSERVICES 10 MODEL SHM LDBAL N *MACHINES DEFAULT: APPDIR

  • Repetitive error message on Calendar

    Hi, I'm having issues with my calendar. The error only applies to my Mac Calendar, I use the same synced calendar on my iphone and ipad and they work fine. Basically every time I open Calendar on the Mac I get an error box pop up as hopefully shown i