cx_Oracle.SessionPool 連線池

wpgy發表於2020-01-18

官網地址:

The example below shows how to connect to Oracle Database using a connection pool:
# Create the session pool
pool = cx_Oracle.SessionPool("hr", userpwd,
        "dbhost.example.com/orclpdb1", min=2, max=5, increment=1, encoding="UTF-8")

# Acquire a connection from the pool
connection = pool.acquire()

# Use the pooled connection
cursor = connection.cursor()
for result in cursor.execute("select * from mytab"):
    print(result)

# Release the connection to the pool
pool.release(connection)

# Close the pool
pool.close()

Applications that are using connections concurrently in multiple threads should set the threaded parameter to True when creating a connection pool:
# Create the session pool
pool = cx_Oracle.SessionPool("hr", userpwd, "dbhost.example.com/orclpdb1",
              min=2, max=5, increment=1, threaded=True, encoding="UTF-8")

Python Callback
If the sessionCallback parameter is a Python procedure, it will be called whenever acquire() will return a newly created database connection that has not been used before. It is also called when connection tagging is being used and the requested tag is not identical to the tag in the connection returned by the pool.
An example is:
# Set the NLS_DATE_FORMAT for a session
def initSession(connection, requestedTag):
    cursor = connection.cursor()
    cursor.execute("ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI'")

# Create the pool with session callback defined
pool = cx_Oracle.SessionPool("hr", userpwd, "orclpdb1",
                     sessionCallback=initSession, encoding="UTF-8")

# Acquire a connection from the pool (will always have the new date format)
connection = pool.acquire()

If needed, the initSession() procedure is called internally before acquire() returns. It will not be called when previously used connections are returned from the pool. This means that the ALTER SESSION does not need to be executed after every acquire() call. This improves performance and scalability.


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/31560527/viewspace-2673870/,如需轉載,請註明出處,否則將追究法律責任。

相關文章