Archived community.zenoss.org | full text search
Skip navigation
Currently Being Moderated

How To Get A DB Connection From The Pool

VERSION 1 
Created on: Sep 14, 2009 11:16 AM by Noel Brockett - Last Modified:  Apr 20, 2010 3:58 PM by Matt Ray

Instructions for using DB connection pooling.

 

If you need a connection to the events database, use this How To to retrieve a connection and how to put it back into the pool.

The pool

DbConnectionPool is hidden and is accessed through DbAccessBase. It follows the Singleton design pattern, so it'll only actually create one DbConnectionPool. It extends python Queue, so DbConnectionPool is also a synchronized queue and should be thread-safe. DbAccessBase is extended by EventManagerBase, so if you have access to the ZenEventManager (located at /zport/dmd/ZenEventManager) you'll have the ability to get a DB connection.

The code

First you'll need to get an instance of ZenEventManager OR an instance of a class that extends DbAccessBase. Within Zenoss, a ZenEventManager should already be instantiated.

 

Next is the "try" block which should include ANY DB calls. This is where you'll get a connection from the pool with the connect() method. You may pass this around to other methods or create a cursor and make some DB transactions. The try block MUST be completed with a "finally" block that includes the close() method.  You MUST pass the connection object to the close() method. This will insure that even if the code within the "try" breaks, we are not leaking DB connections. If you create more than one connection (more than one connect() call in your try block) you will need to have a corresponding close() call. There is ALWAYS a one-to-one relationship between connect() and close() calls.

 

Here is a block of code that illustrates best practices for using the DbConnectionPool

 

...
zem = self.dmd.ZenEventManager
try:
    conn1 = zem.connect()
    conn2 = zem.connect()
    curs1 = conn1.cursor()
    ...
    curs2 = conn2.cursor()
    ...
    # do work
    ...
    curs3 = conn1.cursor()
    ...
finally:
    zem.close(conn1)
    zem.close(conn2)
...

 

Take a look at EventManagerBase.py and Availability.py for some examples of code using the DbConnectionPool.

Comments (0)