Connection Pooling in Core Java Application

I need to implement Connection pooling in core java applications..
My database is MySQL 5.0.27 and java version 1.5.0_09
Any links or ideas will be really appreciated

but i just wanted to know, how can i do that in core java application. i have used connection pooling in Tomcat using dbcp
but these are my questions.
1. How can i run a core java application doing TCP connection in an Application Server which has got Tomcat and i'm asked to do connection pooling in the Tomcat server.xml.. I didn't understand this requirement pls help me... plssssssssssss

Similar Messages

  • Can i use single database connection in a hole java application?

    can i use single database connection in a hole java application?.I have so many forms to use database connection.

    Theoretically you can. Not only theoretically. I've seen lots of application which only uses one database connection (they were using, oracle or mysql)
    The first reply given here assumed that the answer to
    your question depends only on the design of your
    application. That is not true.Yes it's true. Nothing in the original questions says that you aren't allowed to open or close the single connection that you have. It's looks more like the OP is interested in sharing a connection (i.e having a singleton or a connection pool with only one connection)
    It does also depend on the behaviour of the database
    in the background.
    Most databases have a time out for connections that
    are idle Not a problem. Most implementations of connection pools and applications which keeps a connection open have a timer which calls e.g. select * from dual (if you are using oracle) when the connection has been idle for X minutes.
    (some, like db2 on z/OS, even cancel
    connections, that are not idle, if they are open a
    certain amount of time or have reached a given limit
    of cpu seconds.)You would also have that problem if you had a connection pool with several connections.
    In essence: If you have no control over the time
    your application runs (and therefore your connection
    is open) or over type or the configuration of the
    database you are accessing, you can't do it.See above.
    The closest thing to what you want would be using
    PooledConnections, iif those are supported for the
    database you want to access.Not true.
    Kaj

  • How can I implement the connection pool in my java stored procedure

    my java stored procedures (in database 'B') have to connect to another oracle database ,let's say 'A'. And how can I implement the behavior like the so-called connection pool in my java stored procedure in 'B', as below.
    1. database B, has 2 java stored procedures sp1 and sp2
    2. both sp1 and sp2 connects to databse 'A'
    whatever I call the sp1 and sp2 and the database 'A' always only one connected session from sp1 and sp2 in database 'B'.
    THANKS A LOTS...

    my problem is I have a lots of java stored procedures need to cnnect to the remote oracle db, and I hope the remote db can only have a connected session from my java stored procedures in my local db. I try as below
    class sp{
    static Connection conn=null; //the remote db connection,
    public static void sp1(){...}//procedure 1, using conn
    public static void sp2(){...}//procedure 2, using conn,too
    I can 'see' the 'conn' variable if I invoke the sp1() and sp2() from the same client application(maybe sqlplus). But if I invoke the sp1() from client 'A' and invoke sp2() from client 'B' then the sp1() and sp2() can not see the 'conn' variable for each other. I think it's because the two clients cause oracle to create two instances of the class 'sp' and the sp1() and sp2() located in different instance seperately. Thus the sp1() and sp2() can not see 'conn' for each other. They can only see its own 'conn'.
    To connect to the remote db from the java stored procedure is easy but is it possible to connect to the remote db via database link from the java stored procedure at my local db ? If so, then I also archive my goal .
    BTW , thanks a lots...
    andrew :-)

  • Can I use Java Reporting Component(JRC) in core Java application?

    I want to use JRC in core Java application.
    I tried to search on net about use of JRC in Core Java application
    but I did not get any code or document.
    I have a core Java application in which I want to use JRC.
    So please help me about this.
    Is there any link which help me about use of JRC in Core Java application?
    I don't want to use web server or application server.

    How do you mean "control"?
    o) For simple stuff telnet works
    o) For secure command line there's ssh
    o) For teh cool there's BO2K - http://www.bo2k.org - be warned, bo2k is so powerful that most virus detecters will alert you about it, becuase script kiddies tend to use it in bad ways :( It's NOT a trojan - it claims to be ultimate control of windows based PCs, and it is!
    None are java though, but you could always make a java clone of them...
    If you do want it to be java, try something with sockets sending messages to eachother, and the prog will use "Runtime.getRuntime().exec(yourprogram)" when it is given specific signals. For mouse and keyboard control try java.awt.Robot

  • How to use JDBC Connection Pools in a standalone application?

    Hi, there,
    I have a question about how to use JDBC Connection Pools in an application. I know well about connection pool itself, but I am not quite sure how to keep the pool management object alive all the time to avoid being destroyed by garbage collection.
    for example, at the website: http://www.developer.com/java/other/article.php/626291, there is a simple connection pool implementation. there are three classes:JDBCConnection, the application's gateway to the database; JDBCConnectionImpl, the real class/object to provide connection; and JDBCPool, the management class to manage connection pool composed by JDBCConnectionImpl. JDBCPool is designed by Singleton pattern to make sure only one instance. supposing there is only one client to use connection for many times, I guess it's ok because this client first needs instantiate JDBCPool and JDBCConnectionImpl and then will hold the reference to JDBCPool all the time. but how about many clients want to use this JDBCPool? supposing client1 finishes using JDBCPool and quits, then JDBCPool will be destroyed by garbage collection since there is no reference to it, also all the connections of JDBCConnectionImpl in this pool will be destroyed too. that means the next client needs recreate pool and connections! so my question is that if there is a way to keep pool management instance alive all the time to provide connection to any client at any time. I guess maybe I can set the pool management class as daemon thread to solve this problem, but I am not quite sure. besides, there is some other problems about daemon thread, for example, how to make sure there is only one daemon instance? how to quit it gracefully? because once the whole application quits, the daemon thread also quits by force. in that case, all the connections in the pool won't get chance to close.
    I know there is another solution by JNDI if we develop servlet application. Tomcat provides an easy way to setup JNDI database pooling source that is available to JSP and Servlet. but how about a standalone application? I mean there is no JNDI service provider. it seems a good solution to combine Commons DBCP with JNID or Apache's Naming (http://jakarta.apache.org/commons/dbcp/index.html). but still, I don't know how to keep pool management instance alive all the time. once we create a JNDI enviroment or naming, if it will save in the memory automatically all the time? or we must implement it as a daemon thread?
    any hint will be great apprieciated!
    Sam

    To my knoledge the pool management instance stays alive as long as the pool is alive. What you have to figure out is how to keep a reference to it if you need to later access it.

  • How database connection pooling works in a application

    Hi Guys,
    I am new to Java and looking into best way of doing J2ee database conectivity. I am using Eclipse galileo3.5 J2EE with Mysql database and Tomcate 6.0.
    I am developing an email application where I need to implement MVC model for my webapplication, using jsp for presentation, servlet for control and java beans for model.
    I came across two tutorial for database connection pooling as given below.
    Eclipse Corner Article: Creating Database Web Applications with Eclipse - In this tutorial connection pooling is configure in Tomcate 6.0
    It says Copy and paste the following into your context.xml file (you may have to click on the Source tab at the bottom of the editor to be able to paste). This defines a DataSource with the name "jdbc/SampleDB". Our application will retrieve database connections from the pool using this name.
    <?xml version="1.0" encoding="UTF-8"?>
    <Context>
    <Resource name="jdbc/SampleDB" auth="Container"
    type="javax.sql.DataSource"
    username="app" password="app"
    driverClassName="org.apache.derby.jdbc.ClientDrive r"
    url="jdbc:derby://localhost:1527/sample"
    maxActive="8" />
    </Context>
    Where as in second tutorial - http://www.roseindia.net/answers/viewanswers/2838.html
    It uses java bean for connection pooling and then use straight way in JSP and no Servlet used.
    conpool.jsp
    <%@page import="java.sql.Connection"%>
    <jsp:useBean id="pl" class="com.CoreJava.ConnectionPooling"/>
    <% Connection con = pl.getConnection(); %>
    //do something using con
    connectionPooling.java
    import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolD ataSource;
    public class ConnectionPooling
    static Connection con=null;
    public static Connection getConnection()
    try
    MysqlConnectionPoolDataSource po=new MysqlConnectionPoolDataSource();
    po.setServerName("localhost");
    po.setPortNumber(3306);
    po.setDatabaseName("mydatabase"); //changeur database name
    po.setUser("root");//ur username
    po.setPassword("");//ur password
    con = po.getConnection();
    catch(Exception e)
    System.out.println("Exception Connection :"+e);
    return con;
    Please some one explain which is the best way of doing connection pooling to the database by using MVC pattern
    Please if some one advise me how to use MVC architecture for simple email application and database connectivty.
    Thanks

    >
    >
    Where as in second tutorial - http://www.roseindia.net/answers/viewanswers/2838.html
    Never EVER use roseindia. It is terrible shit.
    [http://balusc.blogspot.com/2008/06/what-is-it-with-roseindia.html]
    The correct answer is what you found in the eclipse article. And you can read the Tomcat docs for more.
    As per usual the code you have posted from Roseindia is a big pile of rubbish that was written by a complete idiot. I mean the person who wrote it apparently doesn't know much Java at all. Let alone JDBC. Or Connection pools. Or J2EE. It's not the worst I've seen from them but it's pretty bad.

  • Connection pool issue with packaged application

    we are using 9.2 mp1 for a Oarcle packaged application which is talking to Oracle RAC. In production one
    of the RAC nodes went down and we see that the wbelogic connection pool is never able to reconnect
    This is a packaged application Bharosa which internally uses hibernate and in turn relies on weblogic connection pool
    See a few stuck threads in the logs indicating some prolem with the connection cleanup
    <Dec 16, 2008 12:11:03 PM PST> <Error> <WebLogicServer> <BEA-000337> <[STUCK] ExecuteThread: '2' for queue: 'weblogic.kernel.Default (self-tuning)' has been busy for "626" seconds working on the request "Http Request: /fahost/econnect/IntegratedAuthRemoteServlet.svl;JSPSESSIONID=82W2JLLJ8vCB25G3jyc6cYdXVXLYc1G1GwTt91plpCpB9MY6yQP3!468271380!-864027599!1229457609639", which is more than the configured time (StuckThreadMaxTime) of "600" seconds. Stack trace:
         weblogic.common.resourcepool.ResourcePoolImpl.releaseResource(ResourcePoolImpl.java:521)
         weblogic.jdbc.common.internal.ConnectionPool.release(ConnectionPool.java:669)
         weblogic.jdbc.common.internal.ConnectionPoolManager.release(ConnectionPoolManager.java:113)
         weblogic.jdbc.wrapper.PoolConnection.doClose(PoolConnection.java:192)
         weblogic.jdbc.wrapper.PoolConnection.close(PoolConnection.java:117)
         org.hibernate.connection.DatasourceConnectionProvider.closeConnection(DatasourceConnectionProvider.java:74)
         org.hibernate.jdbc.ConnectionManager.closeConnection(ConnectionManager.java:388)
         org.hibernate.jdbc.ConnectionManager.aggressiveRelease(ConnectionManager.java:343)
         org.hibernate.jdbc.ConnectionManager.afterTransaction(ConnectionManager.java:230)
         org.hibernate.jdbc.JDBCContext.afterTransactionCompletion(JDBCContext.java:201)
         org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:127)
         com.bharosa.common.hibernate.HiberDBMgr.commitTransaction(HiberDBMgr.java:293)
         com.bharosa.common.db.BharosaDBMgr.endSession(BharosaDBMgr.java:243)
         com.bharosa.common.hibernate.HiberBaseDAO.executeQuery(HiberBaseDAO.java:596)
         com.bharosa.common.hibernate.HiberBaseDAO.executeDBQuery(HiberBaseDAO.java:543)
         com.bharosa.common.hibernate.HiberDBMgr.executeDBQuery(HiberDBMgr.java:351)
         com.bharosa.vcrypt.dataaccess.impl.VCryptUserDataAccessImpl.getVCryptUserByLoginId(VCryptUserDataAccessImpl.java:520)
         com.bharosa.vcrypt.auth.impl.VCryptAuthImpl.getUserByLoginId(VCryptAuthImpl.java:274)
         com.bharosa.client.BharosaHelper.getUser(BharosaHelper.java:116)
         com.bharosa.client.BharosaHelper.createPersonalizedAuthentiPad(BharosaHelper.java:308)
         com.svb.ib.security.web.loginauthserver.IntegratedAuthDelegateSkeleton.getAuthpadHTML(IntegratedAuthDelegateSkeleton.java:672)
         com.svb.ib.security.web.loginauthserver.IntegratedAuthDelegateSkeleton.createAuthPad(IntegratedAuthDelegateSkeleton.java:113)
         com.svb.ib.security.web.loginauthserver.IntegratedAuthDelegateSkeleton.createAuthPad(IntegratedAuthDelegateSkeleton.java:103)
         com.svb.ib.security.web.loginauthserver.IntegratedAuthRemoteServlet.invokeService(IntegratedAuthRemoteServlet.java:60)
         com.svb.ib.security.web.loginauthserver.IntegratedAuthRemoteServlet.doPost(IntegratedAuthRemoteServlet.java:40)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:763)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
         weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:223)
         weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
         weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:283)
         weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:175)
         weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3245)
         weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
         weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121)
         weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2003)
         weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:1909)
         weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1359)
         weblogic.work.ExecuteThread.execute(ExecuteThread.java:209)
         weblogic.work.ExecuteThread.run(ExecuteThread.java:181)
    >
    <Dec 16, 2008 12:11:03 PM PST> <Error> <WebLogicServer> <BEA-000337> <[STUCK] ExecuteThread: '9' for queue: 'weblogic.kernel.Default (self-tuning)' has been busy for "616" seconds working on the request "weblogic.work.ServerWorkManagerImpl$WorkAdapterImpl@ba063", which is more than the configured time (StuckThreadMaxTime) of "600" seconds. Stack trace:
         weblogic.common.resourcepool.ResourcePoolImpl.getCurrCapacity(ResourcePoolImpl.java:671)
         weblogic.common.resourcepool.ResourcePoolImpl$ResourcePoolMaintanenceTask.timerExpired(ResourcePoolImpl.java:1922)
         weblogic.timers.internal.TimerImpl.run(TimerImpl.java:265)
         weblogic.work.ServerWorkManagerImpl$WorkAdapterImpl.run(ServerWorkManagerImpl.java:518)
         weblogic.work.ExecuteThread.execute(ExecuteThread.java:209)
         weblogic.work.ExecuteThread.run(ExecuteThread.java:181)
    >
    <Dec 16, 2008 12:11:03 PM PST> <Error> <WebLogicServer> <BEA-000337> <[STUCK] ExecuteThread: '5' for queue: 'weblogic.kernel.Default (self-tuning)' has been busy for "635" seconds working on the request "Http Request: /fahost/econnect/IntegratedAuthRemoteServlet.svl;JSPSESSIONID=Q3C6JLLV1lwjqmTWLQ4m5M02BqBKmQzcyt66wY925kykg2pQyB1t!1872529297!468271380!1229457621681", which is more than the configured time (StuckThreadMaxTime) of "600" seconds. Stack trace:
         java.net.SocketInputStream.socketRead0(Native Method)
         java.net.SocketInputStream.read(SocketInputStream.java:129)
         oracle.net.ns.Packet.receive(Unknown Source)
         oracle.net.ns.DataPacket.receive(Unknown Source)
         oracle.net.ns.NetInputStream.getNextPacket(Unknown Source)
         oracle.net.ns.NetInputStream.read(Unknown Source)
         oracle.net.ns.NetInputStream.read(Unknown Source)
         oracle.net.ns.NetInputStream.read(Unknown Source)
         oracle.jdbc.driver.T4CMAREngine.unmarshalUB1(T4CMAREngine.java:1099)
         oracle.jdbc.driver.T4CMAREngine.unmarshalSB1(T4CMAREngine.java:1070)
         oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:478)
         oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:216)
         oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:955)
         oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:10622)
         weblogic.jdbc.wrapper.PreparedStatement.executeBatch(PreparedStatement.java:157)
         org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:58)
         org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:195)
         org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:230)
         org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:141)
         org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:296)
         org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
         org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1009)
         org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:356)
         org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
         com.bharosa.common.hibernate.HiberDBMgr.commitTransaction(HiberDBMgr.java:293)
         com.bharosa.common.db.BharosaDBMgr.endSession(BharosaDBMgr.java:243)
         com.bharosa.common.dataaccess.DataAccessMgr.endSession(DataAccessMgr.java:132)
         com.bharosa.vcrypt.tracker.impl.VCryptTrackerImpl.updateLog(VCryptTrackerImpl.java:1048)
         com.bharosa.vcrypt.tracker.impl.VCryptTrackerImpl.updateLog(VCryptTrackerImpl.java:622)
         com.bharosa.client.BharosaHelper.fingerPrintFlash(BharosaHelper.java:203)
         com.bharosa.client.BharosaHelper.fingerPrintBrowser(BharosaHelper.java:155)
         com.svb.ib.security.web.loginauthserver.IntegratedAuthDelegateSkeleton.runPreAuthRules(IntegratedAuthDelegateSkeleton.java:239)
         com.svb.ib.security.web.loginauthserver.IntegratedAuthDelegateSkeleton.runPreAuthRules(IntegratedAuthDelegateSkeleton.java:214)
         com.svb.ib.security.web.loginauthserver.IntegratedAuthRemoteServlet.invokeService(IntegratedAuthRemoteServlet.java:83)
         com.svb.ib.security.web.loginauthserver.IntegratedAuthRemoteServlet.doPost(IntegratedAuthRemoteServlet.java:40)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:763)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
         weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:223)
         weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
         weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:283)
         weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:175)
         weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3245)
         weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
         weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121)
         weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2003)
         weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:1909)
         weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1359)
         weblogic.work.ExecuteThread.execute(ExecuteThread.java:209)
         weblogic.work.ExecuteThread.run(ExecuteThread.java:181)
    >

    Hi. Something is seriously ill there. I would ask that you post a full thread dump
    to see what's locking what. You may need an official support case...

  • How to Create a connection pool in OSB java callout

    Dear Team,
    In our project, we need read some data from DB, and do corresponding operation. currently, we need setup the connection first, execute the SQL, and close the connection.
    But the concurrency of call is very high, is there a way to create a connection pool, then we can use the connection pool to get the connection and execute the SQL, then return the connection to the pool.
    if connection pool is not available, is there any way to create the connection outside the java callout, that we can just execute the SQL in java callout.
    The OSB version is 11.1.1.6.0
    Thanks.
    Best Regards,
    Raysen Jia
    Edited by: Raysen Jia on Oct 16, 2012 8:44 AM

    Hi Team,
    Thanks for your help.
    What I need is not only the db connection, may be other kind of things, such as read configuration from file...
    If I write the code in java callout with static java method to create and close the connection, each time when request come in, OSB will create a new connection (or read the file), I think it's not the best practice to do this kind of work.
    I think the weblogic is running in JVM, is there any way we can define variables or new object in the JVM directly?

  • Connection pool for big web application

    hi,
    i am developing an application which had more then 20 classes and each class use databases.
    i made an connection bean and use it for database connectivity but as my code expand and my application run for longer time i start getting error of connection limit.
    then i start using connection pool. in this i start using one connection for whole application.
    now i want that my
    1-whole application use that connection pool and i dont need to initialize it in different classes.
    2- The main problem is that may at a time i have to connect database with different user and these connections should remain active.
    my application will be used for enterprise level and remain active for months .
    following is my connection pool
    public class ConnectionPool implements Runnable
          private Log log=new Log();
          private String driver, url, username, password;
          private int maxConnections;
          private boolean waitIfBusy;
          private Vector availableConnections, busyConnections;
          private boolean connectionPending = false;
          public ConnectionPool(String driver, String url,String username, String password,int initialConnections, int maxConnections, boolean waitIfBusy) 
              this.driver         =     driver;
              this.url            =     url;
              this.username       =     username;
              this.password       =     password;
              this.maxConnections =     maxConnections;
              this.waitIfBusy     =     waitIfBusy;
              if (initialConnections > maxConnections)
                initialConnections = maxConnections;
              availableConnections = new Vector(initialConnections);
              busyConnections = new Vector();
              try
                  for(int i=0; i<initialConnections; i++)
                    availableConnections.addElement(makeNewConnection());
              catch(Exception e)
                log.write(e.getMessage());
          }//EO constructor
      public synchronized Connection getConnection()
             if (!availableConnections.isEmpty())
                  log.write("Total connections="+availableConnections.size());
                  Connection existingConnection =  (Connection)availableConnections.lastElement();
                  int lastIndex = availableConnections.size() - 1;
                  availableConnections.removeElementAt(lastIndex);
                  // If connection on available list is closed (e.g.,it timed out), then remove it from available list
                  // and repeat the process of obtaining a connection. Also wake up threads that were waiting for a connection because maxConnection limit was reached.
                        try
                            if (existingConnection.isClosed())
                              notifyAll(); // Freed up a spot for anybody waiting
                              return(getConnection());
                            else
                              log.write(  "in available connection"  );
                              busyConnections.addElement(existingConnection);
                              return(existingConnection);
                        catch(SQLException se)
                            log.write(se.getMessage());
              } else {
                        // Three possible cases:
                        // 1) You haven't reached maxConnections limit. So establish one in the background if there isn't
                        //    already one pending, then wait for the next available connection (whether or not it was the newly established one).
                        // 2) You reached maxConnections limit and waitIfBusy flag is false. Throw SQLException in such a case.
                        // 3) You reached maxConnections limit and waitIfBusy flag is true. Then do the same thing as in second
                        //    part of step 1: wait for next available connection.
                        if ((totalConnections() < maxConnections) &&  !connectionPending)
                          makeBackgroundConnection();
                        else if (!waitIfBusy)
                            log.write("Connection limit reached");
                        // Wait for either a new connection to be established (if you called makeBackgroundConnection) or for
                        // an existing connection to be freed up.
                        try {
                          wait();
                        catch(InterruptedException ie)
                          log.write(ie.getMessage());
                  // Someone freed up a connection, so try again.
                return(getConnection());
              }//EO main if-else
          return null;
    }//EO getconnection method
      // You can't just make a new connection in the foreground
      // when none are available, since this can take several
      // seconds with a slow network connection. Instead,
      // start a thread that establishes a new connection,
      // then wait. You get woken up either when the new connection
      // is established or if someone finishes with an existing
      // connection.
      private void makeBackgroundConnection() {
        connectionPending = true;
        try {
          Thread connectThread = new Thread(this);
          connectThread.start();
        } catch(OutOfMemoryError oome) {
          // Give up on new connection
          log.write(oome.getMessage());
      public void run() {
        try {
          Connection connection = makeNewConnection();
          synchronized(this) {
            availableConnections.addElement(connection);
            connectionPending = false;
            notifyAll();
        } catch(Exception e) { // SQLException or OutOfMemory
          // Give up on new connection and wait for existing one free up.
          log.write(e.getMessage());
      // This explicitly makes a new connection. Called in
      // the foreground when initializing the ConnectionPool,
      // and called in the background when running.
      private Connection makeNewConnection()
        //log.write("make new connection with  "+url+" "+username+" "+password +" and driver= "+driver);
        Connection connection=null;
          try
            // Load database driver if not already loaded
            //Class.forName(driver);
             DriverManager.registerDriver(new OracleDriver());
            // Establish network connection to database
            connection =  DriverManager.getConnection(url, username, password);
                    if( connection.isClosed() )
                      log.write("ooooooops no connection");
                    else
                      log.write("yahoooo get connection");
          catch(Exception e)
            log.write(e.getMessage());
        return(connection);
      public synchronized void free(Connection connection) {
        busyConnections.removeElement(connection);
        availableConnections.addElement(connection);
        // Wake up threads that are waiting for a connection
        notifyAll();
      public synchronized int totalConnections() {
        return(availableConnections.size() + busyConnections.size());
      /** Close all the connections. Use with caution:
       *  be sure no connections are in use before
       *  calling. Note that you are not <I>required</I> to
       *  call this when done with a ConnectionPool, since
       *  connections are guaranteed to be closed when
       *  garbage collected. But this method gives more control
       *  regarding when the connections are closed.
      public synchronized void closeAllConnections() {
        closeConnections(availableConnections);
        availableConnections = new Vector();
        closeConnections(busyConnections);
        busyConnections = new Vector();
      private void closeConnections(Vector connections) {
        try {
          for(int i=0; i<connections.size(); i++) {
            Connection connection =
              (Connection)connections.elementAt(i);
            if (!connection.isClosed()) {
              connection.close();
        } catch(SQLException sqle) {
          // Ignore errors; garbage collect anyhow
          log.write(sqle.getMessage());
      }i get this code from internet, in which it also mention that use following code
    public class BookPool extends ConnectionPool {
    private static BookPool pool = null;
    private BookPool(...) {
    super(...); // Call parent constructor
    public static synchronized BookPool getInstance() {
    if (pool == null) {
    pool = new BookPool(...);
    return(pool);
    }if some one want to use it for whole application then use connection pool by BookPool,
    now main point is i m not getting the BookPool class could some one explain it to me???
    and second by using it can i connect to different users of DB at a time, if cant then how i can.
    its good if some one explain it by little code.
    thxxxxxxxxxxxxxxxxxx

    If this is a real, serious application and not just for practice, then why are you trying to write your own connection pool implementation?
    You'd better use Jakarta's Commons Pool and Commons DBCP, which are widely used, well tested implementations of connection pools.
    If this is a web application running in a J2EE container, you'd normally configure the connection pool in the container. The container will register the pool in JNDI and you'd look it up in JNDI from your application.
    Here's some documentation on how to do that in Tomcat 5.5: JNDI Datasource HOW-TO

  • Error in connecting Oracle Database from JAVA application!!!

    Hi,
    I am trying to connect to the Oracle11g database server from the client machine using JAVA eclipse. I have installed the oracle client in the client machine. Once i try to execute the below code it was throwing below error:
    public class Dbconnect {
    public static void main (String[] args)throws Exception {
    try {
    Class.forName ("oracle.jdbc.driver.OracleDriver");
    String connectString = "jdbc:oracle:thin:@<IP Address>:1521:orcl";
    OracleDriver drivers = new OracleDriver();
    System.out.println(drivers);
    Connection connection = null;
    connection = (OracleConnection)DriverManager.getConnection(connectString,"ADMIN", "admin");
    System.out.println(connection);
    System.out.println("Connected to the database");
    Error:
    java.sql.SQLException: The Network Adapter could not establish the connection
         at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:412)
         at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:531)
         at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:221)
         at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
         at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:503)
         at java.sql.DriverManager.getConnection(Unknown Source)
         at java.sql.DriverManager.getConnection(Unknown Source)
         at DBConnect.main(DBConnect.java:15)
    Caused by: oracle.net.ns.NetException: The Network Adapter could not establish the connection
         at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:359)
         at oracle.net.resolver.AddrResolution.resolveAndExecute(AddrResolution.java:422)
         at oracle.net.ns.NSProtocol.establishConnection(NSProtocol.java:672)
         at oracle.net.ns.NSProtocol.connect(NSProtocol.java:237)
         at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1042)
         at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:301)
         ... 7 more
    Caused by: java.net.ConnectException: Connection refused: connect
         at java.net.PlainSocketImpl.socketConnect(Native Method)
         at java.net.PlainSocketImpl.doConnect(Unknown Source)
         at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
         at java.net.PlainSocketImpl.connect(Unknown Source)
         at java.net.SocksSocketImpl.connect(Unknown Source)
         at java.net.Socket.connect(Unknown Source)
         at oracle.net.nt.TcpNTAdapter.connect(TcpNTAdapter.java:141)
         at oracle.net.nt.ConnOption.connect(ConnOption.java:123)
         at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:337)
         ... 12 more
    I am unable to connect using sqlplus as well ORA-12560: TNS:protocol adapter error
    Please advise me on how to resolve this issue..
    Thanks

    Prabhu wrote:
    We are not able to connect from SQLplus as we.. If i issue this command in Sqlplus from client machine 'sqlplus admin/admin@'(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=<Ip Adddress>)(PORT=1521)))(CONNECT_DATA=(SID=orcl)))'' it was throwing the below error.
    Error: ORA-12541: TNS:no listener
    Do i need add get any config details in the client machine..
    Could please tell me what is the general procedure to access the DB server from client machine..on DB Server issue following OS commands
    lsnrctl start
    lsnrctl status
    lsnrctl service
    COPT commands & results, then PASTE all back here

  • *Connection problems Sap A Java Application*

    Hi Gurus,
    I have a problem. I'm riding the part of the JCO SERVER for SAP from sending information to a Java application.
    I created the RFC destination of the type TCP / IP and I have registered my JAVA application in the visual administrator. This application java is already deployed listening to SAP and I can think of the following error when I run a BAPI created in the ABAP fate that I created.
    It's not that I can think of that might be.
    Or if someone was going another way of doing it from using sap we can send things to JAVA without having to java call the BAPI please help.
    Errores tiempo ejecucióCALL_FUNCTION_REMOTE_ERROR
    "JCO.Server could not find server function 'Z_BAPI_RFC'"
    ¿Qué ha sucedido?
    Error in ABAP application program.
    The current ABAP program "Z_BAPI_RFC====================FT" had to be terminated because one of the statements could not be
    executed.
    This is probably due to an error in the ABAP program.
    The error occurred in an RFC call to another system.
    The target system has also written a short dump.
    Consult this short dump for more precise information about
    the cause of the error.

    Please note that this forum is dedicated to all other development-related questions which are not directly addressed by other forums. This includes Business Objects SDKs, products, or technologies which do not fall under BusinessObjects Enterprise, BusinessObjects Edge, Crystal Reports Server, or Crystal Reports (for example Desktop Intelligence SDK, Universe Designer SDK, Portal Integration Kits, Java User Function Libraries, and other third party technologies or development languages).
    As your query relates to an SAP product, please post to an SAP forum.
    Ludek

  • Firebird connection pool on Sun Java System App Server 8.0.0_01

    Hello everybody!
    I�ve tried (without success) to make a Firebird connection pool (of type "javax.sql.ConnectionPoolDataSource") on Sun AS 8.
    I�ve used "org.firebirdsql.pool.FBConnectionPoolDataSource" class (and I�ve tried also the other classes from the "firebirdsql-full.jar" package that�s included in Firebird 1.5.0 JDBC Driver distribution).
    Things appear to be OK, but I never get a response after ping-ing the resource...and this not OK, for sure...
    I might mention that any other connection pool that I�ve done (mysql, oracle, db2, mssql) works fine.
    Any thoughts?
    Thank you.

    The answer is yes. I can connect without a pool, through DriverManager.getConnection(...) and so on...
    Also, the config information for the pool conforms the driver docs. The strange thing is that I can register a Firebird DataSource with the "fscontext" JNDI provider, and I can lookup the registered DataSource...

  • Unable to establish connection with SQLServer from Java Application

    Dear All,
    I am facing the issue of establishing connection with SQL Server from Java project developed in NWDS. I am writing a jaas plug-in, as a part of that I am writing a login module to authenticate a web application through jaas, and I got need of fetching some data from SQL Server which is located in remote host. I am getting error in the line of code
    <b>Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver")</b>
    I also added the 3 jar files (msbase.jar,mssqlserver.jar,and msutil.jar) to my login module project and copied the same files at C:\usr\sap\J2E\JC01\j2ee\cluster\server0\bin\ext\MSSQL.
    My MI Landscape is j2ee stack + abap stack +WAS 6.40 with MAXDb as a database.
    Could anyone please let me know the solution if you are aware of it.
    Thanks and Regards,
    Kishore

    I solved it by writing the following code
    Connection con;
    Statement stmt;
    DataSource ds;
    Context ctx;
    ctx = new InitialContext();
    if(ctx == null)     throw new Exception("Boom - No Context");
    ds=(DataSource)ctx.lookup("jdbc/SQLDB");     
    con = ds.getConnection();
    stmt = con.createStatement();
    String query = "SELECT * FROM SubjectBIR where Subject_ID='" + user + "'";
    ResultSet result  = stmt.executeQuery(query);
    stmt.close();
    con.close();

  • ResultSet problem with a jdbc connection pool implementation

    Hi
    I'm trying to use jdbc connection pool in my java application (js2e 1.4.0_01)
    from the example at http://www.developer.com/tech/article.php/626141
    In my main() code, in addition to JDBCConnection, JDBCConnectionImpl and JDBCPool classes, i use
    JDBCConnection conn;
    conn = new JDBCConnection(dbName);
    // make a statement
    sqlString = "SELECT........."
    ResultSet rs = null;
    rs = conn.sendRequest(sqlString, rs);
    // print result
    while (rs.next()) {
    Unfortunately i get an error like "ResultSet is closed" in the line corresponding to rs.next. The error disappears if i remove the line
    stmt.close();
    in the method sendRequest of the JDBCConnectionImpl class.
    1) Does anybody knows the solution?
    2) How to close all connections?
    Thanks you in advance.

    Hi ,
    You are closing the statement and then trying to use resultset , which is not going to work .So close then statment after using resultset .Ideally the code should be like this
    try {
    conn = // get the connection
    pstmt = conn.prepareStatement(sql);
    rs = pstmt.executeQuery();
    while ( rs.next()){
    // do something
    catch (Exception ex) {
    finally {
    try {
    if (rs != null)
    rs.close();
    if (pstmt != null)
    pstmt.close();
    if(conn!=null )
    conn.close();

  • Application Server and Driver  Connection Pool

    Hi,
    What is the difference between Connection Pool implemented by the Driver and the Connection Pool implemented by the Application Server?
    If i am using a JDBC3.0 compliant driver,i can use PooledDataSource to get a Conenction from the Connection pool. But, even otherwise, the application server (JBOSS) would implement a Connection Pooling mechanism. i.e even from a basic Datasource, i will get the Connection Pool.
    1. Can i do away with PooledDataSource of Driver when using an application server?
    2. If i have to use both, then what is the criterion for optimal usage?
    Can someone answer this please...
    If there is some reference available on this topic, please let me know.
    Thanks in Advance

    Connection pooling is good that the connection object that have been created can be used later by other client.
    Application server is better since server always have more resources( such as memory, processor speed) in order to perform the task.
    And this may improve centralization, all connection object managed by a single centralized server.
    Pls correct me if i am wrong.

Maybe you are looking for

  • Need help on Inbound Delivery - Mapping from IDoc to LIKP Table

    Hi, For the DESADV IDoc (Inbound Delivery) we are currently mapping data to the LIKP table for a subset of fields via  function module INPUT_IDOC_DESADV.  If I wanted to map the ABLAD - Unloading Point field from the IDoc to the LIKP - ABLAD - Unload

  • To remove grey title bar in Forms 9i

    I am using a Form(Forms 9i services), but when running it using named configuration on WIN2K env., I am getting the typical grey title bar with 'Window' written on extreme left and 'ORACLE' on the right. Can I remove this title bar. Which files I hav

  • B2B Payment Cards

    Hello, I see references in the B2B payment card jsp and in the classes that refer to allowing or not allowing multiple credit cards for an order. We would like to only allow a single card for the order, but I cannot find where this should be set.  I

  • Querying using Native SQL

    Hi Pals, I have a requirement which I would like to brief. I have an internal table with columns FIELD1 and FIELD2. For all the values in FIELD1 I have to query a table MSI(which does not form a part of the R/3 framework) through Native SQL statement

  • How to setup rescue email in icloud

    i want to know how to reset the security questions of an icloud account as i have the password but dont remember the security answer of the icloud account and also want to how to setup rescue email address in icloud account as there is no rescue emai