恢复在psycopg2中创建的连接池

2024-04-23 23:43:55 发布

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

代码如下

import psycopg2
from psycopg2 import pool
try:
    postgreSQL_pool = psycopg2.pool.SimpleConnectionPool(1, 20,user = "postgres",
                                              password = "pass@#29",
                                              host = "127.0.0.1",
                                              port = "5432",
                                              database = "postgres_db")
    if(postgreSQL_pool):
        print("Connection pool created successfully")

    # Use getconn() to Get Connection from connection pool
    ps_connection  = postgreSQL_pool.getconn()

    if(ps_connection):
        print("successfully recived connection from connection pool ")
        ps_cursor = ps_connection.cursor()
        ps_cursor.execute("select * from mobile")
        mobile_records = ps_cursor.fetchall()

        print ("Displaying rows from mobile table")
        for row in mobile_records:
            print (row)

        ps_cursor.close()

        #Use this method to release the connection object and send back to connection pool
        postgreSQL_pool.putconn(ps_connection)
        print("Put away a PostgreSQL connection")

except (Exception, psycopg2.DatabaseError) as error :
    print ("Error while connecting to PostgreSQL", error)

finally:
    #closing database connection.
    # use closeall method to close all the active connection if you want to turn of the application
    if (postgreSQL_pool):
        postgreSQL_pool.closeall

假设我们将代码包装在函数中。类似的方法,如果我们按照代码创建另一个函数,我们需要再次创建连接池

我认为不要关闭连接池,而是重新使用它的不同功能

我们如何找到现有的池并重用它

谢谢


Tags: theto代码fromimportifpostgresqlpostgres