python - Correct use of psycopg3 - Stack Overflow

admin2025-04-16  3

I am studying the psycopg3 library for working with postgresql, I wanted to know if I applied the correct approach to working with psycopg3. I recently learned what pool connections are, so I wrote the following code:

from flask import Flask
from psycopg_pool import ConnectionPool

app = Flask(__name__)
pool = ConnectionPool(conninfo='dbname=test user=test password=test',min_size=4, max_size=10)

@app.route("/")
def index():
    with pool.connection() as conn:
        ans = conn.execute("SELECT * FROM users;").fetchall()
        return {"result": ans}

Before this I just created a connection using the old approach but I didn't know about the pool:

from flask import Flask
import psycopg2

app = Flask(__name__)

def db_connect():
    conn = psycopg2.connect(database="test", user="test",
        password="test.", host="localhost", port=5432)
    return conn

@app.route("/")
def index():
    with db_connect() as conn:
        with conn.cursor() as cur:
            cur.execute("SELECT * FROM users;")
            ans = cur.fetchall()
            return {"result": ans}

I would like to know if I am using and programming psycopg3 correctly.

转载请注明原文地址:http://anycun.com/QandA/1744814338a87987.html