使用psycopg2的Python数据库池

2024-10-05 12:26:16 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是一个数据库池示例。我不明白以下几点。在

  1. 为什么getcursor函数使用“yield”?在
  2. 什么是上下文管理器?在

从psycopg2.pool导入SimpleConnectionPool 从contextlib导入contextmanager

    dbConnection = "dbname='dbname' user='postgres' host='localhost' password='postgres'"

    # pool define with 10 live connections
    connectionpool = SimpleConnectionPool(1,10,dsn=dbConnection)

    @contextmanager
    def getcursor():
        con = connectionpool.getconn()
        try:
            yield con.cursor()
        finally:
            connectionpool.putconn(con)

    def main_work():
        try:
            # with here will take care of put connection when its done
            with getcursor() as cur:
                cur.execute("select * from \"TableName\"")
                result_set = cur.fetchall()

        except Exception as e:
            print "error in executing with exception: ", e**

Tags: defaswithpostgresconpooldbnameyield
1条回答
网友
1楼 · 发布于 2024-10-05 12:26:16

你的两个问题都是相关的。在python中,当您看到with语句时,我们使用的就是上下文管理器。经典地说,它们是这样写的。在

class getcursor(object):
    def __enter__(self):
        con = connectionpool.getconn()
        return con

    def __exit__(self, *args):
        connectionpool.putconn(con)

现在,当您使用上下文管理器时,它将在with语句上调用__enter__方法,并在退出上下文时调用__exit__方法。就这样想吧。在

^{pr2}$

@contextmanager装饰器是一种使创建上下文管理器更容易的糖。基本上,它使用yield语句将执行返回给调用者。直到并包括yield语句的所有内容都是__enter__方法,之后的所有内容都是__exit__语句。在

相关问题 更多 >

    热门问题