ITPub博客

首页 > 自动化运维 > DevOps > cx_Oracle.SessionPool 连接池

cx_Oracle.SessionPool 连接池

DevOps 作者:wpgy 时间:2020-01-18 09:00:54 0 删除 编辑

官网地址:https://cx-oracle.readthedocs.io/en/latest/user_guide/connection_handling.html#connection-pooling

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博客 ” ,链接:https://blog.itpub.net/31560527/viewspace-2673870/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
擅长: Oracle、MySQL, Python、PHP、Web 开发; 研究领域:数据库技术、自动化运维

注册时间:2018-11-01

  • 博文量
    29
  • 访问量
    39461